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

时间:2017-10-04 08:34:33

标签: angular angular2-routing

我们已在路由文件 app-routing.module.ts 中配置preloadingStrategy: PreloadAllModules,以便在首页加载时加载所有模块。因为它有点滞后,我们希望在加载最后一个模块之前显示加载动画。这可能吗?

应用-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;
    }
}

1 个答案:

答案 0 :(得分:0)

我自己想出了办法。我不知道这是不是正确的方式,但它对我有用。我只是检查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;
    }
}