Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use fetched config in forRoot

I'm writing an angular app which uses @ngx-translate. With TranslateModule.forRoot(...) i provide a TranslateLoader:

@NgModule({
  imports: [
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient, ConfigService, LogService]
      }   
    })     
  ]
})

Also i have a ConfigService which loads an config.json utilizing APP_INITIALIZER.

The problem is, the TranslateLoader needs an url from the config. But forRoot() runs before APP_INITIALIZER which leads to ConfigService not having loaded the config and an empty url.

Is there another way to do this?

Currently i'm thinking about manually bootstrapping angular.

like image 900
phylax Avatar asked Mar 05 '18 15:03

phylax


1 Answers

For anyone still looking at this, I found a way to load translations using the TranslateLoader provider after App Init. The ngx-translate lib allows you to override the current loader. So we can pass a new factory after the app has completed bootstrapping.

export function HttpLoaderFactory(handler: HttpBackend, valueAvailableAfterInit) {
  const http = new HttpClient(handler);
  return new TranslateHttpLoader(http, valueAvailableAfterInit, '.json');
}

export class AppModule {
  constructor(
    private translate: TranslateService,
    private handler: HttpBackend
  ) {}

  ngDoBootstrap() {
    const valueAccessableAfterBootstrap = `I'll leave this to your use-case. For me it is an environment variable overwritten via ngOnInit in app.component`;

    this.translate.currentLoader = HttpLoaderFactory(this.handler, valueAccessableAfterBootstrap); // replace loader
    this.translate.reloadLang('en-US').pipe(take(1)).subscribe(); // reload translations with new loader
  }
}
like image 133
Alex Grant Avatar answered Nov 13 '22 00:11

Alex Grant