这里有Stackblitz https://stackblitz.com/edit/angular-parse-object REST API的响应格式为
[{"id":123,"name":Test,"value":{"pass": true, "verified": true}}, {"id":435,"name":Test12,"value":{"pass": false, "verified": true}},]
<div *ngFor="let record of student.value">
<ul *ngFor="let key of objectKeys(record)">
<li>{{key}} :: {{record[key]}}</li>
</ul>
</div>
获取错误**无法读取未定义的属性'value'**
<div *ngFor="let rec of student">
<h2>{{rec.id}}</h2>
<div *ngFor="let result of rec.value">
<h4> {{value.pass}} </h4>
</div>
</div>
获取类型为“字符串”的错误对象。 NgFor仅支持绑定到Iterables,例如数组。
如何解决?
我希望输出为
ID : 123 Name : Test Pass : true [yes] verified : true
答案 0 :(得分:0)
您只需要1个ngFor
,您的值就不是数组。
<div *ngFor="let rec of student">
<h2>Id: {{rec.id}} Name: {{rec.name}} Pass: {{rec.value.pass}} Verified: {{rec.value.verified}}</h2>
</div>
参考(您可以格式化) https://stackblitz.com/edit/angular-iterator
已更新:
像这样用JSON.parse更改地图功能
this.student = ["{pass: true, verified: true}", "{pass: false, verified: true}"];
this.student = this.student.map(c=>JSON.parse(c.replace(/([a-zA-Z0-9-]+): ([a-zA-Z0-9-]+)/g, "\"$1\":\"$2\"")));
答案 1 :(得分:0)
我只是使用您的学生数组写一个基本的ngFor
代码。试试这个,希望对您有所帮助。谢谢
HTML
<div class="studentList" *ngFor="let student of students">
<ul>
<li>ID : {{student.id}}</li>
<li>Name : {{student.name}}</li>
<li>Pass : {{student.value.pass}} [{{student.value.pass ? 'Yes' : 'No'}}]</li>
<li>Verified : {{student.value.verified}}</li>
</ul>
</div>
TS
students = [
{
"id":123,
"name":"Test",
"value":{"pass": true, "verified": true}
}, {
"id":435,
"name":"Test12",
"value":{"pass": false, "verified": true}
}
]
CSS
.studentList ul {
list-style: none;
margin: 0 0 10px;
padding: 0;
}
.studentList ul li {
display: inline-block;
margin-right: 10px;
}