We can easily code split and lazy load a route in Angular. However when the user then clicks that lazy loaded route, it make some time to actually fetch and run the JavaScript bundle. In this lesson we‘ll see how we can implement a loading indicator for such lazy loaded routes.
<!-- app.component.thml --> <router-outlet> <span class="loader" *ngIf="loading"></span> </router-outlet>
import { Component } from ‘@angular/core‘; import { Router, RouteConfigLoadStart, RouteConfigLoadEnd, RouterEvent } from ‘@angular/router‘; @Component({ selector: ‘app-root‘, templateUrl: ‘./app.component.html‘, styleUrls: [‘./app.component.css‘] }) export class AppComponent { loading: boolean; constructor(router: Router) { this.loading = false; router.events.subscribe( (event: RouterEvent): void => { if (event instanceof RouteConfigLoadStart) { this.loading = true; } else if (event instanceof RouteConfigLoadEnd) { this.loading = false; } } ); } }
原文地址:https://www.cnblogs.com/Answer1215/p/11420056.html
时间: 2024-10-26 02:28:26