I have a service in angular 2 that in its current form only listens to events from a custom dispatcher, acts on them and sends other events through the dispatcher.
So the service isn't injected anywhere nor do I want it to (it will later be injected in components of lazily loaded modules).
The service resides in a shared module and I export it like so:
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [Dispatcher, AccountService]
};
}
}
How do I make sure it gets instantiated when SharedModule loads?
You can use NgModule's constructor. In this example I'm using it to instantiate UserService and replaceReducers() for ngrx/store when I lazy load this module:
@NgModule({
declarations: [],
imports: [
CommonModule,
...
],
providers: [
UserService,
...
],
})
export class LazyModule {
constructor(
private userService: UserService,
private store: Store<any>) {
console.info(`replaceReducer(${ModuleRootReducer.name})`);
this.store.replaceReducer(ModuleRootReducer);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With