首页 > 解决方案 > ngOnInit() 中的 Angular Transloco 用法

问题描述

我知道下面的代码不起作用,因为翻译文件en.json还没有加载,什么时候ngOnInit()被调用:

组件.ts

ngOnInit() {
  console.log(this.translocoService.translate('hello', { value: 'world' }););
}

en.json

{
  "hello": "Hello",
}

另一种方法是订阅:

ngOnInit() {
  this.translocoService.selectTranslate('hello', { value: 'world' }).subscribe(value => console.log(value));
}

但在我的组件中,我有 30 个键需要翻译。我真的应该订阅所有 30 个密钥吗?

演示: https ://stackblitz.com/edit/ngneat-transloco-8xqjqm?file=src%2Fapp%2Fapp.component.ts

标签: angulartransloco

解决方案


我认为您应该组织您的 JSON 翻译文件,使其具有包含组件所需的所有 30 种翻译的父属性(我们称之为父属性parentAttribute,但要找到一个更好的名称;)):

{
  "parentAttribute": {
    "child1": "translation1"
    ...
    "child30": "translation30"
  }
}

然后,您应该使用transloco 服务提供的translateObject 方法:

const translations = this.translocoService.translateObject('parentAttribute');

translations变量应包含:

{
    "child1": "translation1"
    ...
    "child30": "translation30"
}

推荐阅读