-1

I have a root AppModule module.

There are two modules HeaderModule and FooterModule:

@NgModule({
  providers: [Test2Service],
})
export class HeaderModule {}

@NgModule({
  providers: [Test2Service],
})
export class FooterModule {}

As you can see each other has own provider Test2Service.

After all I import these modules to main module AppModule:

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    CommonModule,
    HeaderModule,
    FooterModule,
  ]

Why when I make changes in Test2Service it has effect in both modules, in components?

  • What do you exactly want to do by Test2Service? bcoz if you make any changes in service then it will be reflected in all other instances of the same service. – er-sho Mar 23 '21 at 12:53
  • Check it on https://stackoverflow.com/questions/40089316/how-to-share-service-between-two-modules-ngmodule-in-angular-not-between-to-c – Himanshu Patni Mar 23 '21 at 12:56

2 Answers2

0

https://angular.io/guide/singleton-services Services in Angular are singletons meaning there is only one instance. If you are using Angular 6+, you should use the providedIn: 'root' decorator and not put it in any providers array in any modules. Also, putting the service in multiple provider arrays is not recommended, it should only be provided in one place.

To make a service non-singleton, you can provide it in the component decorator as shown here

This is a really good blog post. You should check it out.

AliF50
  • 16,947
  • 1
  • 21
  • 37
-1

If your modules are lazily loaded, Try providedIn any

@Injectable({
 providedIn: 'any'
})
YogendraR
  • 2,144
  • 12
  • 17