Avoid Multiple Service Instances in Lazy Loaded Modules in Angular

Share this video with your friends

Send Tweet

Shared Angular modules may export components as well as services which are meant to be reused across the entire application. Whenever you want to use an exported component, in another module, you need to import the module defining that component accordingly. Services on the other hand are globally registered, there is one instance per dependency injector. However, there is something you should be aware of: Lazy loaded modules have their own dependency injector. As a result, importing shared modules in a lazy loaded module, may result in multiple instances of a service being available in the app. In this lesson we will learn about the ModuleWithProviders interface that helps avoid such situations.

Stephan Maier-Knodt
Stephan Maier-Knodt
~ 7 years ago

Thanks from the north of the Alps! Very short, very clear all-encompassing. Nothing to add.

Juri Strumpflohner
Juri Strumpflohner(instructor)
~ 7 years ago

haha 😀. Thank you, glad you liked it 👍

Adallo
Adallo
~ 7 years ago

Nice one. Thanks

Viktor Soroka
Viktor Soroka
~ 7 years ago

As I understand it would also work fine if the service was imported in app module and forRoot thing is just to keep the service in the related module. Is not it?

Juri Strumpflohner
Juri Strumpflohner(instructor)
~ 7 years ago

@Viktor: Exactly. But usually you want to keep services in the modules where they belong. The forRoot() is a convention that is being used for providers & which you usually do just once in your root module (i.e. the AppModule). This way providers are registered to the top-most dependency injection container & therefore available to all other modules. However, your imported module might not just export providers, but also components, directives and pipes. For those you need to import your "shared module" on all other modules where you plan to use those components. But there you don't call .forRoot() again and thus you won't get the providers again

Viktor Soroka
Viktor Soroka
~ 7 years ago

@Juri, thank you for you quick replies) Have been waiting for you next courses.

Juri Strumpflohner
Juri Strumpflohner(instructor)
~ 7 years ago

@Viktor :) thanks man. I have some I'm currently working on and a couple of cool ones that I'll start very soon. So stay tuned for more stuff to come along 🙂

Levi9
Levi9
~ 6 years ago

Nice and clear. Love it.

ganqqwerty
ganqqwerty
~ 5 years ago

is it the same as providedIn:root?