Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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?

like image 321
Vítor França Avatar asked Oct 14 '25 08:10

Vítor França


1 Answers

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.

like image 160
danday74 Avatar answered Oct 19 '25 04:10

danday74



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!