Angular 2 - 在 preloadingStrategy 执行期间显示加载动画

Angular 2 - Show load animation during preloadingStrategy execution

我们在路由文件 app-routing.module.ts 中配置了 preloadingStrategy: PreloadAllModules 以在第一个页面加载时加载所有模块。因为它有点滞后,所以我们想显示一个加载动画,直到加载最后一个模块。这可能吗?

app-routing.component.ts:

@NgModule({
    imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })],
    exports: [RouterModule]
})

我们已经实现了重新路由的 gif 动画。

app.component.ts:

router.events.subscribe((routerEvent: Event) => {
    this.checkRouterEvent(routerEvent);
});
....

checkRouterEvent(routerEvent: Event): void {
    if (routerEvent instanceof NavigationStart) {
       this.loading = true;
    }

    // this.loading is just a boolean to show <div> with animation inside or not.
    if (routerEvent instanceof NavigationCancel ||
       routerEvent instanceof NavigationEnd ||
       routerEvent instanceof NavigationError) {
       this.loading = false;
    }
}

我自己想出了一个办法。我不知道这是否是正确的方法,但它对我有用。我只是在检查 RouteConfigLoadStartRouteConfigLoadEnd 事件。

private numberOfLoadingModules: number = 0;
private numberOfLoadedModules: number = 0;

checkRouterEvent(routerEvent: Event): void {
    // Used for site init. For each module which will be loaded this event is fired
    if (routerEvent instanceof RouteConfigLoadStart) {
       this.loading = true;
       this.numberOfLoadingModules += 1;
    }

    // Used for site init. For each module which has been loaded this event is fired
    if (routerEvent instanceof RouteConfigLoadEnd) {
       this.numberOfLoadedModules += 1;
    }

    // Check if all modules are completly loaded. Needed because of lagging if preloadStrategy is used (in app-routing).
    if (this.numberOfLoadedModules == this.numberOfLoadingModules) {
       this.loading = false;
    }

    if (routerEvent instanceof NavigationStart) {
       this.loading = true;
    }

    if (routerEvent instanceof NavigationCancel ||
       routerEvent instanceof NavigationEnd ||
       routerEvent instanceof NavigationError) {
       this.loading = false;
    }
}