Home > OS >  Singleton service across AppModule and library
Singleton service across AppModule and library

Time:04-01

Context

I have an angular app containing two libraries: DashboardLib and ChartsLib. On a component of my app I have a dashboard from DashboardLib and the dashboard itself use charts from ChartsLib. I need to define a global timer to synchronize my charts. So, I created a service TimerService in ChartsLib handling setInterval of my Subject to synchronize the charts.

The charts are listening to the timer service and the root app is starting the timer.

Problem

I tried to Inject my service using providedIn: 'root' (even providedIn: 'platform') and forRoot(), but I still can't have a shared service between the root app and the library itself.

I assume I did not understand how work shared services, however I don't know how to solve my problem.

Thank you for your responses.

CodePudding user response:

providedIn: 'root' is correct however you also need include an @NgModule declaration in your library if you aren't already and include the service as a provider. The root app then needs to include the module in its imports.

Library

@NgModule({
  declarations: [
   ...
  ],
  imports: [
    ...
  ],
  providers: [
    TimerService
  ],
  exports: [
    ...
  ]
})  
export class LibModule {}

Root App

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    LibModule 
  ], 
})
export class AppModule { }

The TimerService should also be included as an export in your public-api.ts file in the library if it isn't already.

  • Related