Monday, 4 November 2019

Angular: Pass parameters to NgModule

I have modules that use TranslateModule from ngx-translate (the question is not about this lib but about Angular). It looks something like this:

@NgModule({
  ...
  imports: [
    TranslateModule.forChild({
      loader: {
        provide: TranslateLoader,
        useFactory: (http: HttpClient) => new TranslateHttpLoader(http, './assets/i18n/todos/', '.json'),
        deps: [HttpClient]
      },
      isolate: true
    })
  ]
})
export class TodosModule {
}

Now there are 5 modules that look like this one. I decided to move TranslateModule to SharedModule. But here is a problem: I have to set a path for each module individually (for ex. ./assets/i18n/todos). That's what I found:

@NgModule({
  ...
  imports: [
    TranslateModule
  ],
  exports: [
    TranslateModule
  ]
})
export class SharedModule {

  static forChild(i18path: string): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
        {
          provide: TranslateModule,
          useValue: TranslateModule.forChild({
            loader: {
              provide: TranslateLoader,
              useFactory: (http: HttpClient) => new TranslateHttpLoader(http, `./assets/i18n/${i18nPath}/`, '.json'),
              deps: [HttpClient]
            },
            isolate: true
          })
        }
      ]
    }
  }

}

But it doesn't work. TranslateHttpLoader does not load translation files. No errors in the console. What am I doing wrong?



from Angular: Pass parameters to NgModule

No comments:

Post a Comment