如何使用Angular 5翻译带参数的通知消息?

时间:2019-02-15 06:59:40

标签: javascript angular typescript ngx-translate

我无法使用 ngx-translate / core

翻译通知消息的参数

代码示例

en.json :
   "message": {
        "Successfully removed account": "Successfully removed account"
        }

上面是翻译json

constructor(private translate: TranslateService,
private userService : userService)

async deleteAccount(account) {
try {
  await this.userService.removeuserAccount(account.id);
  this.notificationService.sendSuccess(this.translate.instant(`message.Successfully removed account ${account.id}`));
} catch (err) {
  this.notificationService.sendError(this.translate.instant(`message.Unable to delete account: ${err.message}`));
    }
  }

请帮助我解决这个问题

我们需要在组件的链接中修复与此问题类似的问题 https://github.com/ngx-translate/core/pull/990

2 个答案:

答案 0 :(得分:0)

更新:

由于消息来自JSON,因此您需要使用

this.translate.instant(message['Successfully removed account'] + account.id)

上级答案:

如果message.Successfully也是ENUM之类的组件变量,则

使用${message.Successfully} removed account ${account.id}作为反引号(`)中方法的参数

如果不支持反引号并且message.Successfully只是一个字符串,请使用

this.translate.instant("message.Successfully removed account " + account.id) 

如果message.Successfully不是字符串,并且如果是变量,则使用

this.translate.instant(message.Successfully + "removed account " + account.id) 

答案 1 :(得分:0)

尝试此答案。 翻译它并附加到变量。

    constructor(private translate: TranslateService,
    private userService : userService)

    async deleteAccount(account) {
    try {
      await this.userService.removeuserAccount(account.id);
      var status = this.translate.instant('message.Successfully  removed account');
this.notificationService.sendSuccess(this.translate.instant(status + `${account.id}`));
    } catch (err) {
var statuserr = this.translate.instant(`message.Unable to delete account:');
      this.notificationService.sendError(this.translate.instant(statuserr +` ${err.message}`));
        }
      }