Skip to content
Advertisement

Shared module imported in AppModule

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement