Ngx translate with shared/lazy loading modules Ngx translate with shared/lazy loading modules angular angular

Ngx translate with shared/lazy loading modules


I solved this by doing the following:

  1. Create a SharedModule, with below code

SharedModule

export function HttpLoaderFactory(http: HttpClient) {  return new TranslateHttpLoader(http);}@NgModule({  declarations: [],  imports: [    CommonModule,    TranslateModule.forChild({      loader: {      provide: TranslateLoader,      useFactory: HttpLoaderFactory,      deps: [HttpClient]    },    isolate: false}),  ],  exports: [TranslateModule],})export class SharedModule {  static forRoot(): ModuleWithProviders {    return {      ngModule: SharedModule,      providers: [ShoppingCartService, AccountService]    }  }}

So this makes sure that for every module that imports SharedModule, TranslateModule will use the same configuration. Make sure to export it. The forRoot() also solved making sure that ShoppingCartService and AccountService are only one instance and not every lazy-module creating a separate service.

  1. Change AppModule:

AppModule

@NgModule({  declarations: [    AppComponent  ],  imports: [    HttpClientModule,    BrowserModule,    AppRoutingModule,    TranslateModule.forRoot({      loader: {        provide: TranslateLoader,        useFactory: HttpLoaderFactory,        deps: [HttpClient]      },      isolate : false    }),    SharedModule.forRoot(),    ContrySelectorModule,      ],  providers: [    ],  bootstrap: [AppComponent]})export class AppModule { }

Since AppModule is your main entry point, do the forRoot() call here to TranslateModule and the SharedModule.

  1. Any lazy loaded module just has to import SharedModule without any method calls. Also CountrySelectorModule in my example has to just import SharedModule and nothing else.