如何在 Angular 6+ 中使用插值显示 json 字符串的 属性?

How to show property of json string using interpolation in Angular 6+?

假设我们有一个像这样的 JSON 对象列表:

data = {
   id: 1,
   someObjAsString: '{"p1":"a", "p2": "b"}',
   ...
   ... other properties
}

使用 *ngFor 我想显示来自 someObjAsString 的 p2:

<div *ngFor="let data of dataList">
{{data.someObjAsString.p2}} <!-- What should I do here to display p2 property of someObjAsString-->
</div

JSON.parse() 绝对不起作用

如有任何帮助,我们将不胜感激。

因为someObjAsString是对象,所以可以使用keyvalue管道:

<div *ngFor="let item of dataList.someObjAsString | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>

通常ngFor用于遍历数组。

更新:

由于您的对象存储为字符串,因此我们可以使用 json.parse() 构造 JavaScript 值或对象:

data = {
  id: 1,
  someObjAsString: '{"p1":"a", "p2": "b"}',
  anotherObj: '{"p1":"a", "p2": "b"}'
};


ngOnInit(){
    for (const key in this.data) {
        if (this.data.hasOwnProperty(key)) {
             this.data[key] = JSON.parse(this.data[key]);
        }
     }
     console.log(this.data);
}

和HTML:

<div *ngFor="let item of data | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value | json}}</b>

    <div *ngFor="let someObj of item | keyvalue">
        someObj Key: <b>{{someObj.key}}</b> 
          and someObjValue: <b>{{someObj.value | json}}</b>
    </div>
</div>

A complete workstackblitz example can be see here.