如何获得加载Angular LazyModule文件的进度?

时间:2019-07-12 21:24:34

标签: angular angular-router

我试图弄清楚如何显示加载Angular LazyLoaded模块的进度指示。

enter image description here

我可以更改预加载策略,但是是否有钩子可以订阅加载进度?

export class MyPreloadingStrategy implements PreloadingStrategy {
    preload(route: Route, load: Function): Observable<any> {
        return of(true).pipe(flatMap(_ => load()));
    }
}

是否可以订阅load至少知道何时加载?

1 个答案:

答案 0 :(得分:1)

您可以订阅Router.events https://angular.io/guide/router#router-events

  

RouteConfigLoadStart

     

在路由器延迟加载路由配置之前触发的事件。

     

RouteConfigLoadEnd

     

延迟加载路由后触发的事件。

假设您的路线如下:

{
  path: 'lazy', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule)
}

这是您如何挂接到该模块的加载过程的方法:

import { RouteConfigLoadEnd, RouteConfigLoadStart, Router } from '@angular/router';

...
constructor(private router: Router) {
  router.events.subscribe((
    event => {
      if (event instanceof RouteConfigLoadStart && event.route.path === 'lazy') {
        console.log('START');
      }
      if (event instanceof RouteConfigLoadEnd && event.route.path === 'lazy') {
        console.log('FINISH');
      }
    }));
}