我正在编写一个使用@ ngx-translate的角度应用程序。使用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。
还有其他办法吗?
目前我正在考虑手动引导角度。
答案 0 :(得分: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
}
}