角度翻译服务,在嵌套的json

时间:2017-09-03 16:57:28

标签: javascript angular angular-translate

在角度翻译服务中,正常翻译json中的插值参数效果很好。但是在嵌套的json中,插值参数不起作用。

我的JSON:

  "SampleField": {
    "SampleValidation": {
      "MIN": "Value should not be less than {{min}}", 
      "MAX": "Value should not be more than {{max}}", 
    }
  }

My Angular Code:

ngOnInit(): void {
  this.translateService.get('SampleField.Validation', {
    // using hard coded value just as a sample
    min: 0, max: 2000
  }).subscribe(translation => {
    console.log(translation);
  });
}

预期产出:

{
    MIN: "Value should not be less than 0",
    MAX: "Value should not be greater than 2000"
}

实际输出:

{
    MIN: "Value should not be less than {{min}}",
    MAX: "Value should not be greater than {{max}}"
}

2 个答案:

答案 0 :(得分:3)

根据source of ngx-translate插值仅适用于字符串:

export abstract class TranslateParser {
/**
 * Interpolates a string to replace parameters
 * "This is a {{ key }}" ==> "This is a value", with params = { key: "value" }
 * @param expr
 * @param params
 * @returns {string}
 */
abstract interpolate(expr: string | Function, params?: any): string;

这意味着您可能需要使用键数组而不是非叶元素:

this.translateService.get([
    'SampleField.Validation.MIN', 
    'SampleField.Validation.MAX'
  ], {
  // using hard coded value just as a sample
  min: 0, max: 2000
}).subscribe(translation => {
  console.log(translation);
});

答案 1 :(得分:1)

您也可以通过使用 translate 管道来执行此操作,以便您可以删除对组件的附加服务依赖项。

<p *ngIf="!item?.isRemovable">
{{'i18n.dashboard.heading' 
| translate:{'TEXTTOFIND': 'STRINGTOREPLACE'} }}
</p>

只需确保您的密钥 i18n.test.key 已插入此 TEXTTOFIND。类似于下面的内容。

"heading": "This is with the interpolated {{TEXTTOFIND}} text."

注意标题字符串中的 {{}}STRINGTOREPLACE 可以是您想要的任何内容。