2017-10-04 87 views
0

我們在我們的路由文件app-routing.module.ts中配置了preloadingStrategy: PreloadAllModules,以在第一次加載頁面時加載所有模塊。由於它有點滯後,我們希望顯示一個加載動畫,直到加載最後一個模塊。這可能嗎?Angular 2 - 在預加載期間顯示加載動畫策略執行

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

回答

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