ProvidedIn root, any & platform in Angular

The providedIn allow us to specify how Angular should provide the dependency in the service class itself instead of in the Angular Module. It also helps to make the service tree shakable i.e. remove the service from the final bundle if the app does not use it.

ProvidedIn root

Use the ProvidedIn root option, when you want to register the application-level singleton service.

The root option registers the service in the Root Module Injector of the Module Injector tree. This will make it available to the entire application. This is irrespective of whether the service is lazy loaded or eagerly loaded.

If it is never used it will not be added in the final build (tree shaking)

Lazy Loaded Service

Using ProvidedIn root adds it to the Root Module Injector and makes it application-wide singleton

Registering the service in a @NgModule will make it available in that Module only (Singleton within the Module Scope)

Using both makes it singleton for the rest of the application, while it creates a separate instance for that Module

ProvidedIn any

Use ProvidedIn: any when you want every lazy-loaded module to get its own instance of the service.

The eagerly loaded modules always share the instance provided by the Root Module Injector. Hence this will not have any effect on them.

ProvidedIn platform

As per the documents

A special singleton platform injector shared by all applications on the page.

the platform allows us to add the service to the Providers of the Platform Injector. If you recall, the Platform Injector is the parent of the Root Module Injector in the Module Injector tree

This is useful if you have multiple Angular Apps running on a single page.

This is a useful option if you are using Angular Elements, where they can share a single instance of service between them.

Reference

Injectable

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top