0

As per angular document - https://angular.io/guide/singleton-services

If a module defines both providers and declarations (components, directives, pipes), then loading the module in multiple feature modules would duplicate the registration of the service. This could result in multiple service instances and the service would no longer behave as a singleton.

However this is not working in my case - I have one module called as CounterModule which is imported in two different module -

  1. ModuleA
  2. ModuleB

Following is the code -

@NgModule({
  imports: [CommonModule],
  declarations: [CounterComponent],
  exports: [CounterComponent],
  providers: [CounterService],
})
export class CounterModule {}

@NgModule({
  declarations: [ModuleAComponent],
  imports: [CommonModule, CounterModule],
  exports: [ModuleAComponent],
})
export class ModuleA {}

@NgModule({
  declarations: [ModuleBComponent],
  imports: [CommonModule, CounterModule],
  exports: [ModuleBComponent],
})
export class ModuleB {}

<!--Counter component code-->
<button (click)="onIncrement()">Increment</button>
<button (click)="onDecrement()">Decrement</button>
<p>Result - {{ counter }}</p>

<!--Counter component imported in ModuleAComponent-->
<p>Module A Works!</p>
<app-counter></app-counter>

<!--Counter component imported in ModuleBComponent-->
<p>Module B Works!</p>
<app-counter></app-counter>


// Imported both modules in app module
@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ModuleA,
    ModuleB,
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

<!--Showing ModuleA and ModuleB components in AppComponent-->
<app-a></app-a>
<app-b></app-b>

Whenever I click the increment or decrement button same result is shown it both component, i.e same instance of CounterService is getting shared in both feature module, so I am confused about what the document of angular is saying for above

Chris Barr
  • 29,851
  • 23
  • 95
  • 135
user1441238
  • 165
  • 1
  • 2
  • 10
  • See this: https://stackoverflow.com/questions/43282546/non-singleton-services You have to declare the service inside a components `providers` array. Either in `CounterComponent` or within in `AComponent` and `BComponent`. – Eddi Jun 14 '23 at 07:42
  • The documentation used to be clearer, but unless something has changed dramatically, the duplication of the service registration only occurred in lazy loaded feature modules that use the router. – Aluan Haddad Jun 14 '23 at 08:05
  • AluanHaddad , yes the documentation seems to be confusing to me, yes it might be related to lazy loading feature in angular. – user1441238 Jun 15 '23 at 05:04

0 Answers0