角度翻译服务,嵌套json中的插值参数
问题描述:
在角度翻译服务中,正常翻译json中的参数插值效果很好。但是在嵌套的json中,内插参数不起作用。角度翻译服务,嵌套json中的插值参数
我的JSON:
"SampleField": {
"SampleValidation": {
"MIN": "Value should not be less than {{min}}",
"MAX": "Value should not be more than {{max}}",
}
}
我的角度代码:
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);
});
只是一个错字的问题? 'SampleField.Validation' =>'SampleField。 SampleValidation' – dpellier