angularserviceshared-librarieslazy-loading

Angular library service always has a new instance


In Angular 17, There is an Angular library named CommonLib and It contains a WaitSpinnerService which has a private class variable waitSpinner = new EventEmitter();

I use the CommonLib WaitSpinnerService in the AppComponent so I need to import it in the AppModule. I emphasize the WaitSpinnerService is providedIn: 'root'.

In the appComponent's constructor, I listen to the WaitSpinnerService waitSpinner.asObservable via subscribe to turn on or off the wait spinner.

I have a lot of Lazy loaded modules. How it's possible, that when I navigated to a lazy loaded module, always creating a new WaitSpinnerService I see when I navigated to a lazy loaded module, always landed the execution of the constructor of the WaitSpinnerService.

More details about the modules hierarchy: AppModule

SharedModule

Each place the CommonLibModule.forRoot() was used. What will be the right module organization to keep the WaitSpinnerService remains singleton in the App?


Solution

  • you can use this pattern

    @NgModule({
      providers: [WaitSpinnerService]
    })
    export class CommonLibModule {
      static forRoot(): ModuleWithProviders<CommonLibModule> {
        return {
          ngModule: CommonLibModule,
          providers: [WaitSpinnerService]
        };
      }
    }
    

    and then import as like as below

    @NgModule({
      imports: [
        CommonLibModule.forRoot()
      ],
      ...
    })
    export class AppModule {}