【问题标题】:Ionic 4 + Angular - String interpolation to JSON stringIonic 4 + Angular - 字符串插值到 JSON 字符串
【发布时间】:2019-04-24 22:17:16
【问题描述】:

我有以下 JSON,

{
  "commands": [
    {
      "command":"begin ${{password}}",
      "name":"Initialization",
      "description":"Send SMS begin+password"
    }
  ]
}

如何将数据传递给 ${{password}} 以使用传递的值获取填充的字符串?

我尝试使用以下主题中描述的插值函数,但没有任何成功。

Convert a string to a template string

Angular、Ionic 是否为此提供了一些内置函数?

【问题讨论】:

  • 这个 JSON 是你编的,还是你从某个地方得到的?
  • 我可以编辑 JSON 文件。
  • 但是使用单引号的 JSON 不是有效的 JSON。 “命令”:'开始 ${密码}'。我想将变量设置为类范围并将 JSON 值打印到模板。 JSON 中的插值应替换为 Class Scope 中设置的值。

标签: angular ionic-framework ionic4 string-interpolation


【解决方案1】:

var password = 'StackOverflow';
var json_string = `{
  "commands": [
    {
      "command":"begin ${password}",
      "name":"Initialization",
      "description":"Send SMS begin+password"
    }
  ]
}`;

console.log(json_string);

好吧,您可以只使用反引号 (``) 并将其设为 template string,因为您可以按照 cmets 中的讨论编辑 json 文件。此外,您需要有变量值的占位符才能生效。所以把${{password}}改成${password}

【讨论】:

  • 感谢代码 sn-p,但似乎无法动态附加 JSON 内容。私有 modifyData(data:any) { 让 json_string = +JSON.stringify(data)+;返回 JSON.parse(json_string);不更改占位符中的数据。
  • @redrom 你在一个文件中有 json 数据。所以,在文件中有反引号和占位符更改,并在您的modifyData() 中阅读。
【解决方案2】:

经过一番挖掘,以这种方式使用替换解决了:

{
  "commands": [
    {
      "command":"begin |password| and |ipAddress|",
      "name":"Initialization",
      "description":"Send SMS begin+password"
    }
  ]
}

private modifyData(data:any) {
    let stringifiedData  = JSON.stringify(data).replace("|password|", this.password).replace("|ipAddress|", this.ipAddress);
    return JSON.parse(stringifiedData);
  }

结果:

【讨论】:

  • 这不是技术上的模板,而是一个简单的字符串替换。
猜你喜欢
  • 2023-02-20
  • 1970-01-01
  • 1970-01-01
  • 2017-11-28
  • 1970-01-01
  • 2022-06-22
  • 2017-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多