Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate singleton service on module load in Angular2

Tags:

angular

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?

like image 589
Hampus Avatar asked Oct 26 '25 10:10

Hampus


1 Answers

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);
  }
}
like image 155
Sasxa Avatar answered Oct 28 '25 23:10

Sasxa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!