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.
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)
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
Use ProvidedIn: any when you want every lazy-loaded module to
get its own
instance of the service.
@Injectable({
providedIn: 'any'
})
export class SomeService{
}
The eagerly loaded modules always share the instance provided by the Root Module Injector. Hence this will not have any effect on them.
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
@Injectable({
providedIn: 'platform'
})
export class SomeService{
}
We have injected all three services into HelloComponent. The Optional Decorator ensures that if the service not available then the Angular returns null instead of throwing an error.
constructor(
@Optional() private appService: AppService,
@Optional() private eagerService: EagerService,
@Optional() private laztyService: LazyService
)
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.