53

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

Saksham
  • 9,037
  • 7
  • 45
  • 73
Karl Johan Vallner
  • 3,980
  • 4
  • 35
  • 46
  • https://stackoverflow.com/questions/50860898/angular-6-services-providedin-root-vs-coremodule – Manish Jain Jun 14 '18 at 15:22
  • 3
    It is loaded in memory from app start, and used when its is added in constructor by lazy/not lazy module. – Shubhendu Vaid Aug 16 '18 at 10:48
  • 1
    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 Oct 25 '18 at 16:40

1 Answers1

56

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.
Mick
  • 8,203
  • 10
  • 44
  • 66
  • 4
    Is it a decided strategy to use `root` this way? Or must I expect to later on switch over to providing the lazy loaded module in `providedIn: [lazyModule]`? And by `lazy loaded with that module`, does that mean the service is given in a child injector? – Gjert Oct 28 '18 at 17:42
  • 5
    Always use root it is child-proof – Mick Oct 29 '18 at 16:32
  • 3
    Hi. Thanks for the explanation. Could You give quote & source for `2. If the service is only used within a lazy loaded module it will be lazy loaded with that module` ? Thank You. – KarolDepka Apr 26 '20 at 08:37
  • @KarolDepka Sorry but you have to check the two links i posted, or maybe even more of the docs, yourself. I would have to do the same right now. – Mick Apr 28 '20 at 10:47
  • 3
    @KarolDepka https://angular.io/guide/ngmodule-faq#should-i-add-other-providers-to-a-module-or-a-component – eddy May 06 '20 at 20:30