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 {}
当我尝试使用 translate 方法进行翻译时,它第一次不起作用。
constructor(
private translate: TranslocoService
) {
console.log('<< ', this.translate.translate('dashboard.label'));
}
如果我通过路由器移动到另一条路由并返回,则文本会被翻译。似乎您第一次加载应用程序时没有时间加载翻译。有没有办法来解决这个问题?提前致谢。
解决方案
正如文档所说:
请注意,为了安全地使用此方法,您有责任确保翻译文件在调用时已成功加载。如果你不确定,你可以使用 selectTranslate() 方法
此方法返回一个可观察的:
translocoService.selectTranslate('hello').subscribe(value => ...)
translocoService.selectTranslate('hello', { value: 'world' }).subscribe(value => ...)
translocoService.selectTranslate('hello', {}, 'en').subscribe(value => ...)
推荐阅读
- erlang - Erlang 中是否有可用的模块来查找无向图的所有循环?
- java - 将休眠事件记录在与标准输出控制台附加程序不同的文件中
- snowflake-cloud-data-platform - Snowflake SCIM 错误“指定的组成员资格值无效”
- php - 省略包控制器的 `redirect()->action()` 方法的默认控制器命名空间
- qt - 设置弹出高度以包含内容
- typescript - 从 Firebase Cloud Function 调用 Google Books API 时出现 500 错误
- java - 无法使用 scala 解密 OpenSSL 生成的私钥
- performance - 连续调用 fortran 中的同一子例程,性能显着降低
- javascript - 场景光标中断 raycaster
- java - 我无法打开 jar 文件