Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Lifecycle hooks for lazy loaded modules

I am in the process of developing an application using lazy loaded Angular modules.

I have a simple question:

Is it possible to catch an event when a module is loaded?

For example OnInit. This link explains life cycle hooks but it is only for components: Lifecycle hooks for components

I cant find any documentation that explains how to hook in for modules.

Does someone have an idea of how to solve this?

Thanks

like image 598
Diemauerdk Avatar asked Nov 03 '17 11:11

Diemauerdk


2 Answers

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');
  }
}
like image 73
Günter Zöchbauer Avatar answered Oct 29 '22 16:10

Günter Zöchbauer


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');
    }
}
like image 36
kemsky Avatar answered Oct 29 '22 14:10

kemsky