我有一些数据必须在页面加载之前加载,我正在使用路由解析器来实现这一点。下面是我的代码。
服务:
getUsernamesAndBUs(): Observable<any> {
return Observable.forkJoin(
this.http.get('http://localhost:8080/BMSS/getBusinessUnit'),
this.http.get('http://localhost:8080/BMSS/getAllUser'),
this.http.get('http://localhost:8080/BMSS/getCountry'),
this.http.get('http://localhost:8080/BMSS/getCurrency')
);
}
解析器:
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { AgreementDetailsService } from './agreement-details.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class UsernamesAndBusResolveService implements Resolve<any> {
constructor(private agreementDetailsService: AgreementDetailsService) { }
resolve(route: ActivatedRouteSnapshot): Observable<any> {
return this.agreementDetailsService.getUsernamesAndBUs();
}
}
路由模块:
{
path: 'agreement',
canActivate: [CanActivateAuthGuardService],
children: [
{
path: 'create',
component: AgreementComponent,
resolve: { usernamesAndBUs: UsernamesAndBusResolveService }
}
]
}
在路由到的组件中:
this.businessUnits = this.route.snapshot.data['usernamesAndBUs'][0];
this.users = this.route.snapshot.data['usernamesAndBUs'][1];
this.countries = this.route.snapshot.data['usernamesAndBUs'][2];
this.currencies = this.route.snapshot.data['usernamesAndBUs'][3];
在拦截器中:
intercept(httpRequest: HttpRequest<any>, httpHandler: HttpHandler): Observable<HttpEvent<any>> {
if (!this.typeAheads.includes(httpRequest.url.split('/').pop())) {
this.bmssLoaderService.start();
} else {
this.bmssLoaderService.stop();
}
return httpHandler.handle(httpRequest).do((httpEvent: HttpEvent<any>) => {
if (httpEvent instanceof HttpResponse) {
this.bmssLoaderService.stop();
}
}, (error: any) => {
this.bmssLoaderService.stop();
});
}
我使用了一个微调器(使用HttpInterceptor
),它在调用后端服务时显示并在服务返回后消失。现在,即使在后端服务返回后,组件也需要很长时间才能加载,所以在微调器消失后,用户仍然在同一页面上一段时间(大约 10 秒),然后才路由到目标页面。
我不明白是什么导致了这种延迟,我哪里错了。请帮我解决一下这个。