Transloco 翻译第一次不起作用

Jay*_*Jay 2 internationalization angular transloco

这是我的 Transloco 配置:

@Injectable({ providedIn: 'root' })
export class TranslocoHttpLoader implements TranslocoLoader {
  constructor(private http: HttpClient) {}

  getTranslation(lang: string) {
    return this.http.get<Translation>(`/assets/i18n/${lang}.json`);
  }
}

@NgModule({
  exports: [ TranslocoModule ],
  providers: [
    {
      provide: TRANSLOCO_CONFIG,
      useValue: translocoConfig({
        availableLangs: ['en', 'es'],
        defaultLang: 'en',
        // Remove this option if your application doesn't support changing language in runtime.
        reRenderOnLangChange: true,
        prodMode: environment.production,
      })
    },
    { provide: TRANSLOCO_LOADER, useClass: TranslocoHttpLoader }
  ]
})
export class TranslocoRootModule {}
Run Code Online (Sandbox Code Playgroud)

当我尝试使用翻译方法进行翻译时,它第一次不起作用。

constructor(
    private translate: TranslocoService
  ) {
    console.log('<< ', this.translate.translate('dashboard.label'));
  }
Run Code Online (Sandbox Code Playgroud)

如果我通过路由器移动到另一条路线并返回,文本就会被翻译。似乎您第一次加载应用程序时没有时间加载翻译。有没有办法来解决这个问题?提前致谢。

Jay*_*Jay 5

正如文档所说:

请注意,为了安全地使用此方法,您有责任确保在调用该方法时已成功加载翻译文件。如果您不确定,可以使用 selectTranslate() 方法

该方法返回一个可观察值:

translocoService.selectTranslate('hello').subscribe(value => ...)
translocoService.selectTranslate('hello', { value: 'world' }).subscribe(value => ...)
translocoService.selectTranslate('hello', {}, 'en').subscribe(value => ...)
Run Code Online (Sandbox Code Playgroud)

官方文档

  • 如何确保在调用“translate”时翻译文件已成功加载? (3认同)