Angular 2 - Lifecycle hooks for lazy loaded modules

落花浮王杯 提交于 2019-12-05 10:56:09

The constructor of the lazy loaded module should do that

@NgModule({...})
export class MyLazyModule {
  constructor(/* service injection here if required */) {
    console.log('lazy module loaded');
  }
}

There are two router events that you can use: RouteConfigLoadStart and RouteConfigLoadEnd. Also you can use LoadChildrenCallback. These might not do exactly what you want, but still can be helpful.

Also you can use the following trick:

@NgModule({
    imports        : [BrowserModule, FormsModule, RouterModule, ROUTING],
    providers      : [
        {provide: CustomService, useClass: CustomService},
        ...
    ]
})
export class AppModule implements OnInit
{
    //force CustomService service creation or inject other app service,
    // so use can use it to fire event or do smth.
    constructor(handler:CustomService)
    {
        console.log('handler', handler);
        handler.fire('module created');
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!