【问题标题】:Use fetched config in forRoot在 forRoot 中使用获取的配置
【发布时间】:2018-08-13 07:49:28
【问题描述】:

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

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

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

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

还有其他方法吗?

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

【问题讨论】:

  • 你能包含HttpLoaderFactory类的代码吗?

标签: javascript angular ngx-translate


【解决方案1】:

对于仍在关注此问题的任何人,我找到了一种在 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
  }
}

【讨论】:

    猜你喜欢
    • 2017-09-03
    • 2018-09-21
    • 2019-08-30
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 2019-05-19
    • 2019-04-22
    相关资源
    最近更新 更多