簡體   English   中英

使用* ngFor作為顯示有關對象錯誤的數組

[英]Using *ngFor for an array showing error about object

我正在打電話給郵政編碼以解決API。 我想在我的應用程序中顯示地址列表。

public lookupAddresses: any = {};

要進行API調用,我正在使用:

var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');  

this.http.get('https://api.getAddress.io/v2/uk/nn13er?api-key=my-api-key&format=true', {headers:headers}).map(res => res.json().Addresses).subscribe(data => {
    this.lookupAddresses = data
    console.log(data);
}); 

然后在我的模板中,我有:

<ion-list>
    <ion-item *ngFor="let address of lookupAddresses">
        {{ address[0] }}
    </ion-item>         
</ion-list>

但是我得到這個錯誤..

Error in ./RegisterPage class RegisterPage
caused by: Cannot find a differ supporting object 
'[object Object]' of type 'object'. NgFor only supports 
binding to Iterables such as Arrays.

如果我console.log數據的值,那么我得到此結構。

Array[42]
0 : Array[5]
    0 : "10 Watkin Terrace"
    1 : ""
    2 : ""
    3 : "Northampton"
    4 : "Northamptonshire"
    length : 5
1 : Array[5]
    0 : "11 Watkin Terrace"
    1 : ""
    2 : ""
    3 : "Northampton"
    4 : "Northamptonshire"
    length : 5
2 : Array[5]
    0 : "12 Watkin Terrace"
    1 : ""
    2 : ""
    3 : "Northampton"
    4 : "Northamptonshire"
    length : 5      
....

不知道為什么,但是可以解決此問題:

更改:

public lookupAddresses: any = {};

至:

public lookupAddresses: any;

就像你在回答中說的那樣,改變

public lookupAddresses: any = {};

public lookupAddresses: any;

解決問題。 原因是您正在將lookupAddresses的默認值設置為一個空對象,而不是一個數組,或者未定義它。

您的*ngFor嘗試在http請求返回之前循環遍歷lookupAddresses的元素,但是由於{}不是數組,因此*ngFor失敗並顯示錯誤。

如果您改為嘗試該線路

public lookupAddresses: any = [];

這也將起作用,因為*ngFor通過根本不循環來處理空數組,並且以相同的方式來定義undefined。

暫無
暫無

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

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