Ngx translate with shared/lazy loading modules
I solved this by doing the following:
- 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.
- 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
.
- Any lazy loaded module just has to import
SharedModule
without any method calls. AlsoCountrySelectorModule
in my example has to just importSharedModule
and nothing else.