Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 628
Caius Avatar asked Nov 07 '18 09:11

Caius


People also ask

Where should you import a shared module?

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 .

How do I pass data from one module to another in Angular 8?

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.


1 Answers

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

like image 63
Guerric P Avatar answered Sep 20 '22 21:09

Guerric P