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.
Thanks from the north of the Alps! Very short, very clear all-encompassing. Nothing to add.
haha 😀. Thank you, glad you liked it 👍
Nice one. Thanks
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?
@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
@Juri, thank you for you quick replies) Have been waiting for you next courses.
@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 🙂
Nice and clear. Love it.
is it the same as providedIn:root
?