42
votes

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

1
It is loaded in memory from app start, and used when its is added in constructor by lazy/not lazy module. - Shubhendu Vaid
I don't want to load the singleton service in memory from app start, however I do want two different lazy-loaded modules to share the service. What's the prefered way to provide a singleton service to be used by two different lazy-loaded modules without loading it at on start of the app? - Kevin LeStarge

1 Answers

45
votes

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.