//component.ts
public items: any;
getResult(){
var jsonBody = {};
jsonBody['activity'] = this.activity;
jsonBody['seatnumber'] = this.seatNo;
this.localService.postCall(jsonBody)
.subscribe(
data => {
if (data.message === 'ok') {
this.items = data.data.result;
console.log(data.data);
// window.localStorage.setItem('result',data);
}
},
error => {
})
}
//localService.ts
postCall(jsonBody){
const headers = new Headers({
'Content-Type': 'application/json',
'Source': 'WEB'
});
return this.http.post(this.apiUrl, { body: jsonBody }, { headers: headers })
.map(data => {
return data.json();
},
error =>
console.log('unknown error')
);
}
//json object
{
"status": true,
"message": "ok",
"data": {
"result": [
{
"arts": "75",
"studentname": "Archana Kol",
"district": "SIDHI",
"gender": "F",
"agri": "70",
"us": "85",
"fa": "75",
"medium": "Hindi",
"tech": "60",
"hs": "75",
"SchoolDies": "23170515307",
"com": "75",
"seatnumber": 180734668
}
]
}
}
<div *ngFor="let item of items">
{{ item }}
</div>
你好,我使用的是角度2,我想循环遍历这个JSON对象。我可以在控制台上打印这个对象但是当我循环这个对象时,这将显示我的错误“无法找到'对象'类型的不同支持对象'[对象对象]'。NgFor仅支持绑定到诸如数组之类的Iterables “。我该怎么解决这个问题。谢谢
答案 0 :(得分:0)
当您第一次启动该组件时,您的items
变量等于undefined
,这是不可迭代的。
有一些解决方案:
public items:any;
public items:any[] = [];
使用async
管道:
在ngOnInit
:
const headers = new Headers({
'Content-Type': 'application/json',
'Source': 'WEB'
});
this.items$ = this.http.post(this.apiUrl, { body: jsonBody }, { headers: headers })
.map(data => {
return data.json();
},
error =>
console.log('unknown error')
);
然后更改items$: Observable<any[]>
;
最后,将绑定从*ngFor="let item of items"
更改为*ngFor="let item of items | async"
您也可以将{ngFor封装在<div *ngIf="items !== undefined">...</div>
。