正文
[Angular] Show a Loading Indicator for Lazy Routes in Angular
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
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;
}
}
);
}
}