2

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

2 Answers 2

2

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.

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

1 Comment

Great, thank you for sharing your knowledge. Very helpful!
1

Not sure why but this fixes the issue:

Changing:

public lookupAddresses: any = {};

To:

public lookupAddresses: any;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.