I have a structured translation file as follows:
"myApp":{
"errorMessages": {
"unauthorized": "This {{serviceName}} account is not valid for the {{appName}} app.",
"missing_role": "You can not use this account to access {{appName}} application"
}
}
If I access single translation directly, I can easily use interpolation:
const appNameObject = { appName: 'My app', serviceName: 'My Service' };
const unauthorizedErrorMessage = translateService.instant('myApp.errorMessages.unauthorized', appNameObject);
But sometimes I would like to get all keys in a structured object at once - and interpolation seems not to work in this case
const errorMessages = translateService.instant('myApp.errorMessages', appNameObject);
Can I get this working? Thanks
The ngx-translate doesn't support this.
If you want/expect to get an object that looks like this
{
"unauthorized": "This My Service account is not valid for the My app app.",
"missing_role": "You can not use this account to access My app application"
}
You have to actually create it yourself the way you use interpolation in the example that works
Although it can't be done out of the box, you can easily accomplish what you need using JSON.stringify() / JSON.parse() and interpolate by yourself using regular expressions.
Define a function in your utils
service or any other place like this:
const objectInterpolate = (obj: any, params: {[k: string]: any}) => {
return JSON.parse(
JSON.stringify(obj)
.replace(/{{\s*([^}\s]+)\s*}}/gm, (_, group) => params[group] ?? "")
);
}
Then use it in your anywhere:
this.translate.get("myApp.errorMessages")
.subscribe(value => {
this.errorMessages = this.utils.objectInterpolate(
value,
{
paramName: paramValue,
paramName2: paramValue2,
...
}
);
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With