Shared module imported in AppModule
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
Just have a look in this link shared module its not a bad practice to import your shared module in AppModule
Shared module is all about having common modules like if you have form module
some module
which is needed on all your modules instead of importing in all modules you can import it in shared module
and export the same - check the link for further clarification
For service it can be injected just in one module the AppModule
- Services are injectable
and can be used in any module if it has been injected in root module
@Injectable({
providedIn: 'root'
})
Use this decorator in your service top it will automatically inject your service in root module
Thanks - Happy coding !!
As long as you avoid declaring services inside your shared module, I don't see any problem with it.