Angular Singleton Service
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:
- I have 3 Modules in there:
AppModule
,NewModule
, andNotImportedModule
. - I'll be using the services written in the
NewModule
and theNotImportedModule
in theAppModule
'sAppComponent
. NewModule
'sSampleService
is added to theprovides
array of theNewModule
and theNewModule
is added to theimports
array of theAppModule
. And that's why I'm able to use theSampleService
in theAppComponent
.NotImportedModule
is not added to theimports
array of theAppModule
but theAnotherService
isprovidedIn: 'root'
. Hence I'm able to use it in theAppModule
.
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"