0

//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

1

1 Answer 1

0

When you are first starting the component, your items variable is equal to undefined, which isn't iterable.

There's some solutions for that:

  1. change public items:any; for public items:any[] = [];
  2. 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>.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.