Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular service decorator providedIn root effect on lazy loading

I am wondering how the new angular service decorator

@Injectable({     providedIn: 'root' }) 

works in conjuction with lazy loading. Meaning if I have a lazy loaded module, with a service that is providedIn root, will this include the specific service in the applications base code, aka. the app root chunks.js or will this still lazy load the service and later make it a global singleton, when I lazy load that module.

Info on providedIn

https://angular.io/guide/ngmodule-faq

like image 477
Karl Johan Vallner Avatar asked Jun 07 '18 21:06

Karl Johan Vallner


People also ask

What does providedIn root do?

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.

How does Angular handle lazy loading?

To lazy load Angular modules, use loadChildren (instead of component ) in your AppRoutingModule routes configuration as follows. content_copy const routes: Routes = [ { path: 'items', loadChildren: () => import('./items/items. module'). then(m => m.

How do I know if Angular lazy loading is working?

If you want to check how lazy loading works and how lazy loading routing flow, then Augury is the best tool we have. Click on ctrl+F12 to enable the debugger and click on the Augury tab. Click on the router tree. Here, it will show the route flow of our modules.


1 Answers

Yes in this case it will be only part of your lazy-loaded module/chunks. When using providedIn: 'root' the Angular compiler will figure out the perfect way automatically:

  1. The service will be available application wide as a singleton with no need to add it to a module's providers array (like Angular <= 5).
  2. If the service is only used within a lazy loaded module it will be lazy loaded with that module
  3. If it is never used it will not be contained in the build (tree shaked).

For further informations consider reading the documentation and NgModule FAQs

Btw:

  1. If you don't want a application-wide singleton use the provider's array of a component instead.
  2. If you want to limit the scope so no other developer will ever use your service outside of a particular module, use the provider's array of NgModule instead.
like image 115
Mick Avatar answered Sep 18 '22 12:09

Mick