I've read the docs thoroughly and, although I can't find exactly where it's referenced, I have the impression that declaring a service in an eagerly loaded module's providers
array will make the singleton available to the application scope. If this is true,
Is using
@Injectable
providedIn
for any non-lazy-loaded module the same asprovidedIn: "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.
By default, this decorator has a providedIn property, which creates a provider for the service. In this case, providedIn: 'root' specifies that Angular should provide the service in the root injector.
With Angular 9, when we create an @Injectable() service, we have two new options for providedIn: platform and any. According to the documentation, the platform option makes a service available as a singleton with an injector that is shared among all the applications on a page.
With the providedIn: 'root' method, once the lazy loaded chunk containing the service has been registered, it'll be registered at the app's root injector and thus there will only be one global singleton instance.
Yes it is the same.
In general, you should always just use the providedIn: "root" syntax in the @Injectable declaration. It even works with lazy loading when its just loaded in one module, so the service wont be loaded until angular loads the module. Its a way better construct.
I think the only 2 exceptions to prefering providedIn are 1) You want to declare it in a component. This will cause it to not be a singleton, but scoped to the component 2) You are using it in 2 separate, but both lazy loaded modules (and its also not used in the initial load), in this case I believe the best choices is eagerly load it by bringing it into the AppModule on initial load.
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