Skip to content Skip to sidebar Skip to footer

Angular Singleton Service

From my understanding the only difference between using providedIn: 'root' and adding your provider to the providers array of the module is for tree shaking. Currently my applicat

Solution 1:

The error is pretty self-explanatory. IF you do providedIn: 'root', then your service gets registered on the RootInjector. And hence it's basically available to use throughout the App without having to manually add it to the providers array of each of the module that you want to use this service in.

But now that you have removed the providedIn: 'root' from the @Injectable decorator, it will only be available to the Modules where you are adding it to the providers array of those modules. Or it would be available to the modules who are importing the modules that have the service added to the providers array.

Here's a Sample StackBlitz to help you understand this in a better way.

Just to describe:

  1. I have 3 Modules in there: AppModule, NewModule, and NotImportedModule.
  2. I'll be using the services written in the NewModule and the NotImportedModule in the AppModule's AppComponent.
  3. NewModule's SampleService is added to the provides array of the NewModule and the NewModule is added to the imports array of the AppModule. And that's why I'm able to use the SampleService in the AppComponent.
  4. NotImportedModule is not added to the imports array of the AppModule but the AnotherService is providedIn: 'root'. Hence I'm able to use it in the AppModule.

Which would mean that AnotherService would be available to be used throughout the App since it is registered on the RootInjector, since we used providedIn: 'root' on it.

But since SampleService was NOT providedIn: 'root' but was added to the providers array of the NewModule to use it in the AppModule, we had to add the NewModule to the imports array of the AppModule.

Hope it makes more sense with this example.

Post a Comment for "Angular Singleton Service"