Angular singleton service

大憨熊 提交于 2021-01-29 06:14:14

问题


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:

  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.



来源:https://stackoverflow.com/questions/53070689/angular-singleton-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!