首页 > 解决方案 > 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 {}

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

constructor(
    private translate: TranslocoService
  ) {
    console.log('<< ', this.translate.translate('dashboard.label'));
  }

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

标签: angularinternationalizationtransloco

解决方案


正如文档所说:

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

此方法返回一个可观察的:

translocoService.selectTranslate('hello').subscribe(value => ...)
translocoService.selectTranslate('hello', { value: 'world' }).subscribe(value => ...)
translocoService.selectTranslate('hello', {}, 'en').subscribe(value => ...)

官方文档


推荐阅读