In Angular 9 the injectable decorator option providedIn
has a new value called any
. What is the difference between root
and any
?
Is a service considered a singleton in the case that I use any
?
@Injectable({providedIn: 'any'})
class UsefulService {
}
ProvidedIn: any That means there might be multiple instances of the same service. That means that every lazy loaded module has it's own instance of the service. All eagerly loaded modules share one instance provided by the root module injector.
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 is the new Angular way of doing DI. providedIn was brought since Angular 6. The official name is "Tree-shakeable providers" - instead of module providing all its services, it is now the service itself declaring where it should be provided.
providedInlinkDetermines which injectors will provide the injectable.
The difference between the root
and any
as per offical documentation :
root
: The application-level injector in most apps.
platform
: A special singleton platform injector shared by all
applications on the page.
any
: The NgModule injector that receives the resolution.
For more details please refer this article.
Is a service considered a singleton in the case that I use any
? - No
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With