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

我的JSON:

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

我的 Angular 代码:
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}}"
}

最佳答案

根据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);
});

关于javascript - Angular翻译服务,在嵌套json中插值参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46025829/

10-14 02:26