簡體   English   中英

如何訪問復雜的JSON對象Angular 2

[英]how to access complex json object angular 2

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

你好,我正在使用angular 2,我想遍歷這個JSON對象。 我可以在控制台上打印此對象,但是當我循環該對象ngfor時,將向我顯示此錯誤“找不到類型為'object'的其他支持對象'[object Object]'。NgFor僅支持綁定到Iterables,例如數組”。 我該如何解決。 謝謝

首次啟動組件時, items變量等於undefined ,這是不可迭代的。

有一些解決方案:

  1. 更改public items:any; 對於public items:any[] = [];
  2. ngOnInit使用async管道:

     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') ); 

然后更改item items$: Observable<any[]>items$: Observable<any[]> ;

最后,將綁定從*ngFor="let item of items"更改為*ngFor="let item of items | async"

您還可以將* ngFor包裝在<div *ngIf="items !== undefined">...</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM