Angular 2 - 延迟加载模块的生命周期挂钩
Angular 2 - Lifecycle hooks for lazy loaded modules
我正在使用延迟加载的 Angular 模块开发应用程序。
我有一个简单的问题:
是否可以在加载模块时捕获事件?
例如OnInit。 link 解释了生命周期挂钩,但仅适用于组件:Lifecycle hooks for components
我找不到任何说明如何挂接模块的文档。
有人知道如何解决这个问题吗?
谢谢
您可以使用两个路由器事件:RouteConfigLoadStart
和 RouteConfigLoadEnd
。您也可以使用 LoadChildrenCallback
。这些可能无法完全满足您的需求,但仍然会有所帮助。
你也可以使用以下技巧:
@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');
}
}
延迟加载模块的构造函数应该这样做
@NgModule({...})
export class MyLazyModule {
constructor(/* service injection here if required */) {
console.log('lazy module loaded');
}
}
我正在使用延迟加载的 Angular 模块开发应用程序。
我有一个简单的问题:
是否可以在加载模块时捕获事件?
例如OnInit。 link 解释了生命周期挂钩,但仅适用于组件:Lifecycle hooks for components
我找不到任何说明如何挂接模块的文档。
有人知道如何解决这个问题吗?
谢谢
您可以使用两个路由器事件:RouteConfigLoadStart
和 RouteConfigLoadEnd
。您也可以使用 LoadChildrenCallback
。这些可能无法完全满足您的需求,但仍然会有所帮助。
你也可以使用以下技巧:
@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');
}
}
延迟加载模块的构造函数应该这样做
@NgModule({...})
export class MyLazyModule {
constructor(/* service injection here if required */) {
console.log('lazy module loaded');
}
}