Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using @Injectable providedIn for any non-lazy-loaded module the same as providedIn: "root"?

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 as providedIn: "root"?

like image 562
papiro Avatar asked Aug 31 '18 17:08

papiro


People also ask

What is @injectable 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.

What is providedIn root?

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.

What are the new options for providedIn in Angular 9?

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.

When a service is provided for root and is also added to the provider's configuration for a lazy loaded module what instance of that service does the?

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.


1 Answers

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.

like image 191
bgraham Avatar answered Oct 23 '22 11:10

bgraham