The idea here is that we will create a route resolver and then we will subscribe to the router event and on NavigationStart event we will start the spinner and on NavigationEnd and other related events we will stop the spinner. This way new component is not activated until data is fetched to render that component, and until data is being fetched user will be displayed with the spinner.
Route resolver is a service which imports Resolve interface from ‘@angular/router’. Here you implement the resolve method which has two parameters - ActivatedRouteSnapshot and RouterStateSnapshot. This method returns observable of an object which you want to return. In your route configuration, you activate this by adding resolve. Through ActivatedRouteSnapshot, you can get hold of all route-related data for the route being activated, like parameters, query string, etc. Now at this place, you can call your service to interact with the server, before the new component is activated. This way you can handle any error which server may return as well your component is not partially displayed.
To implement spinner, in your application component (app's root component), subscribe to router event method and initialize some variable based on which you can show spinner on the page (using css you can place spinner at the center of the page)
router.events.subscribe(
(event: Event) => {
if (event instanceof NavigationStart) {
this.loading = true;
} else if (
event instanceof NavigationStart ||
event instanceof NavigationEnd ||
event instanceof NavigationCancel ||
event instanceof NavigationError ) {
this.loading = false;
}
});
router.events.subscribe(
(event: Event) => {
if (event instanceof NavigationStart) {
this.loading = true;
} else if (
event instanceof NavigationStart ||
event instanceof NavigationEnd ||
event instanceof NavigationCancel ||
event instanceof NavigationError ) {
this.loading = false;
}
});
ReplyDeleteThanks for sharing the information!
Docker and Kubernetes Training
Docker Training
Docker Online
Docker and Kubernetes Online Training