//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>
hello, i am using angular 2, I want to loop through this JSON object. I am able to print this object on console but when I loop this object ngfor this will display me this error "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." how can I solve this. thank you
When you are first starting the component, your items
variable is equal to undefined
, which isn't iterable.
There's some solutions for that:
public items:any;
for public items:any[] = [];
use async
pipe: in 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') );
Then change items for items$: Observable<any[]>
;
And finally, change your binding from *ngFor="let item of items"
to *ngFor="let item of items | async"
You can also wrap the *ngFor in a <div *ngIf="items !== undefined">...</div>
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.