Angular translate service, interpolate params in nested json

Sye*_*hiq 8 javascript angular-translate ngx-translate angular

In angular translation service, interpolating params in normal translation json works well. But in nested json, interpolating params is not working.

My JSON:

  "SampleField": {
    "SampleValidation": {
      "MIN": "Value should not be less than {{min}}", 
      "MAX": "Value should not be more than {{max}}", 
    }
  }
Run Code Online (Sandbox Code Playgroud)

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);
  });
}
Run Code Online (Sandbox Code Playgroud)

Expected Output:

{
    MIN: "Value should not be less than 0",
    MAX: "Value should not be greater than 2000"
}
Run Code Online (Sandbox Code Playgroud)

Actual Output:

{
    MIN: "Value should not be less than {{min}}",
    MAX: "Value should not be greater than {{max}}"
}
Run Code Online (Sandbox Code Playgroud)

小智 10

根据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;
Run Code Online (Sandbox Code Playgroud)

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

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);
});
Run Code Online (Sandbox Code Playgroud)