Mr. Mars
Mr. Mars

Reputation: 840

Importing the same module twice because of the Shared Service

What happens if I have the following scenario in the main module of my Angular application?

On the app.module.ts I import the module TranslateModule with forRoot() to configure it and make it available to all the application. In the shared.module.ts I export that module so that other modules can use it. In the shared.module.ts I also export services, so I create the forRoot() method and I import it into the app.module.ts.

This way I am importing TranslateModule twice. One directly in the app.module.ts with forRoot form and another one through the shared.module.ts. Is there a problem in doing this? If it exists, how can it be solved?

app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgbModule.forRoot(),
    ComponentsModule,
    DashboardModule,
    OtherModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    }),
    SharedModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})

shared.module.ts

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [],
  exports: [
    TranslateModule
  ]
})
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [CounterService]
    };
  }
}

Upvotes: 0

Views: 3327

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222552

The above approach should work fine. There won't be any issues in doing as above.

Once your app.module.ts configured with ngx-translate you can implement on other modules using shared.module as mentioned in ngx-translate repository, then you don’t need to worry about importing TranslateModule everytime. You only need to add this in your shared.module:

Read more on this.

Upvotes: 1

Related Questions