Reputation: 3256
I have some data that has to be loaded before the page loads and I'm using route resolvers to achieve this. Below is my code.
Service:
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')
);
}
Resolver:
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();
}
}
Routing Module:
{
path: 'agreement',
canActivate: [CanActivateAuthGuardService],
children: [
{
path: 'create',
component: AgreementComponent,
resolve: { usernamesAndBUs: UsernamesAndBusResolveService }
}
]
}
In the component that's routed to:
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];
In interceptor:
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();
});
}
I use a spinner (using HttpInterceptor
) that shows up when back-end service is being called and disappears once the service returns. Now that the component takes long to load even after the back-end service has returned, the user is still on the same page for some time (around 10 seconds) after the spinner has disappeared, before routing to the target page.
I don't get what causes this delay and where am I wrong. Please help me with this.
Upvotes: 3
Views: 1906