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 -
- ModuleA
- 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