Chris
Chris

Reputation: 4728

Using *ngFor for an array showing error about object

I am making a call to a postcode to address API. I want to display the list of addresses in my app.

public lookupAddresses: any = {};

To make my API call I am using:

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

And then within my template I have:

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

But I get this error ..

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.

If I console.log the value of data then I get this structure.

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

Upvotes: 2

Views: 1441

Answers (2)

Adam
Adam

Reputation: 4683

Like you said in your answer, changing

public lookupAddresses: any = {};

to

public lookupAddresses: any;

fixes the problem. The reason is that you're setting the default value of lookupAddresses to an empty object, rather than an array, or leaving it undefined.

Your *ngFor tries to loop through the elements of lookupAddresses, before your http request returns, but because {} isn't an array, the *ngFor fails and prints out an error.

If you instead tried the line

public lookupAddresses: any = [];

it would also work, since *ngFor treats an empty array and undefined the same way, by not looping at all.

Upvotes: 2

Chris
Chris

Reputation: 4728

Not sure why but this fixes the issue:

Changing:

public lookupAddresses: any = {};

To:

public lookupAddresses: any;

Upvotes: 1

Related Questions