angular - 在forRoot中使用fetched config

phy*_*lax 6 javascript ngx-translate angular

我正在写一个使用@ngx-translate的角度应用程序.使用TranslateModule.forRoot(...)我提供了TranslateLoader:

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

我还有一个ConfigService,它使用APP_INITIALIZER加载一个config.json.

问题是,TranslateLoader需要配置中的url.但是forRoot()在APP_INITIALIZER之前运行,导致ConfigService没有加载配置和空URL.

还有另一种方法吗?

目前我正在考虑手动引导角度.

Ale*_*ant 4

对于仍在关注此问题的任何人,我找到了一种在 App Init 后使用 TranslateLoader 提供程序加载翻译的方法。该ngx-translate库允许您覆盖当前加载程序。因此,我们可以在应用程序完成引导后传递一个新工厂。

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
  }
}
Run Code Online (Sandbox Code Playgroud)