Angular项目中如何在TypeScript对象数组内使用ngx-translate翻译
ngx-translate在TypeScript对象数组中使用i18n键的解决方案
问题场景
在Angular项目中使用ngx-translate实现国际化,需要在TypeScript代码的对象数组里调用翻译键获取对应翻译文本。初始实现时遇到两个问题:
- 调用
translate.get()方法返回的是Observable对象,无法直接作为字符串赋值给数组项的text属性 - 改用
translate.instant()方法时,只会返回i18n键名,没有返回对应的翻译内容
初始代码示例:
// 类型定义 interface Shortcut { text: string; icon: string; } shortcutList: Shortcut[] = []; constructor(private translate: TranslateService){} // 数组赋值代码 this.shortcutList = [ { text: this.translate.get('shortcuts.some-key'), icon: 'fa-calendar-alt'}, { text: this.translate.get('shortcuts.some-key2'), icon: 'fa-users'}, { text: this.translate.get('shortcuts.some-key3'), icon:'fa-archway'} ];
项目使用的i18n JSON配置如下:
{ "shortcuts": { "some-key": "对应值1", "some-key2": "对应值2", "some-key3": "对应值3" } }
问题原因与解决步骤
translate.instant()返回键名的核心原因是调用方法时,翻译资源文件还未加载完成,ngx-translate找不到对应键的翻译值,就会直接返回键名本身。- 解决方案是创建Resolver路由预加载器,在页面加载完成前先完成翻译资源的加载,保证业务代码执行时翻译资源已经就绪。
- 预加载配置完成后,修改数组赋值代码为调用
instant方法即可。如果出现部分数组项翻译异常,优先检查i18n配置文件中对应的键名是否存在拼写错误。
最终可运行代码
this.shortcutList = [ { text: this.translate.instant('shortcuts.some-key'), icon: 'fa-calendar-alt'}, { text: this.translate.instant('shortcuts.some-key2'), icon: 'fa-users'}, { text: this.translate.instant('shortcuts.some-key3'), icon:'fa-archway'} ];
内容的提问来源于stack exchange,提问作者Babulaas
相关产品推荐
相关产品推荐

