问题
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 application works fine if I add providedIn: 'root'
it works fine, but if I remove that and add it to the providers array of the module I get the StaticInjectorError
saying it cant find the provider. Has anyone seen this or have an understanding of why this would happen? From the docs I believe that adding it to the providers array should allow this to work
回答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.
来源:https://stackoverflow.com/questions/53070689/angular-singleton-service