ProvidedIn In Angular

ProvidedIn In Angular

In this article, We will learn about the ProvidedIn Root, Any And Platform In Angular. We can use providedIn to tell Angular how to deliver the dependency in the service class itself rather than in the Angular Module. It also aids in making the service tree shakable, i.e. removing a service from the final bundle if it is not used by the app.

ProvidedIn root

When you want to register the application-level singleton service, use the ProvidedIn root option.

The root option adds the service to the Module Injector tree's Root Module Injector. This makes it available to the rest of the app. This is true regardless of whether the service is eagerly or lazily loaded.

It will not be included in the final build if it is never use (tree shaking)

Lazy Loaded Service

Adding it to the Root Module Injector with ProvidedIn root makes it an application-wide singleton.

When you register a service in a @NgModule, it will only be available in that Module (Singleton within the Module Scope)

Using both makes it a singleton for the rest of the app while also creating a separate instance for that Module.

ProvidedIn any

When you want each lazy-loaded module to have its own instance of the service, use ProvidedIn:any.

@Injectable({  
   providedIn: 'any'
})
export class SomeService{
}

The Root Module Injector's instance is always shared by the eagerly loaded modules. As a result, this will have no effect on them.

ProvidedIn platform

All applications on the page share a unique singleton platform injector.

The platform allows us to add the service to the Platform Injector's Providers. In the Module Injector tree, the Platform Injector is the parent of the Root Module Injector.
@Injectable({  
   providedIn: 'platform'
})
export class SomeService{
}

If you have numerous Angular Apps running on a single page, this is beneficial.

If you're using Angular Elements, this is a good solution because they can share a single instance of service.

Conclusion

In this article, We covered ProvidedIn Root, Any And Platform In Angular. We can use providedIn to tell Angular how to deliver the dependency in the service class itself rather than in the Angular Module.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in comment section.

Post a Comment

Previous Post Next Post