简体   繁体   中英

What is the difference between providedIn: 'Root' than using a service as a provider at the app component?

If I set a service as a provider at the app module (root module) or at the decorator @Injectable use providedIn: 'root', I assume that I will achieve the same behavior in both cases. That means all my application will "see" the same singleton class provided by the root module.

But If I don't set any module at the @Injectable decorator on the service and use that class as a provider at the app component module, I am not able to see that same service within components that are not 'created' by my template. For example, I can't use that service inside a MatDialog, that is created and opened using TS and not my template.

That being said, what is the technical difference between those approaches?

They introduced providedIn: 'root' to make it easier to manage services. Most services are stateless singleton services. providedIn: 'root' is essentially the same as just adding the service at the app.module level in the providers array. However, it was easy to forget to add this entry and an unnecessary extra step.

Obviously, if you don't want a singleton service and would rather provide stateful services at various levels then the providers array is still available. It would be confusing to scrap it at the app.module level just because providedIn: root covers this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM