I was reading the Angular documentation about modules, looking for a line that discourages importing a SharedModule inside the AppModule.
I didn't find anything about that, just a GitHub issue which states that it's better not to import it. However without any deep explain...
https://github.com/tomastrajan/angular-ngrx-material-starter/issues/47
Angular discourages providing services in the Shared modules, which indeed I agree. But nothing else.
So my question is:
Since all my feature modules are lazy-loaded, and needs to import the shared module, but also my app component needs to use stuff provided by the same shared module, is it a bad practice to import it into the AppModule?
What may the consequences be?
Thanks in advance to anyone
Import the SharedModule into any module where you need to use shared modules or components. As you can see in the image, App is the name you've passed in the app. component. html .
You can import MemberCardModule into AppModule directly. Or import into ShareModule and import ShareModule into AppModule. It is important to import Modules into AppModule. And then you can you MemberCardModule.
The problem with importing a SharedModule
into the AppModule
is that the providers will be injected twice in the feature modules (once by the SharedModule
, once by the AppModule
) which will result in the services not being singletons as they are supposed to be.
The common pattern to achieve that is not to expose providers directly on the @NgModule
declaration but in a static forRoot
function (the name is not mandatory, it's a convention) like that:
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [
...
]
};
}
}
When importing the SharedModule
into AppModule
, use SharedModule.forRoot()
, when you import it in a feature module just import it as SharedModule
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With