cnak2
cnak2

Reputation: 1841

Can't access an array within my object

I'm a bit of a newbie on Angular (moving from AngularJS)

I have a call I'm making to an api that returns an object with a subdocument (array).

The object returned from the api is basically:

contact:{
  first_name:'Bob',
  last_name:'smith',
  phones:[
    {
      phone_number:'222-222-2222'
      phone_type:'home'
    },
    {
      phone_number:'333-333-3333'
      phone_type:'mobile'
    },
  ]
}

In my html I can call {{contact.first_name}}

But if I try to do a '*ngFor' like this:

*ngFor="let phone of contact.phones"

I get a compilation error saying it can't find 'phones' of 'undefined'.

This does not make senes to me, as I know 'contact' is not undefined and I can see that the full object is returned.

What am I missing?

Upvotes: 0

Views: 36

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222532

Since you are requesting from api with asynchronous call, you need to use *ngIf or use safe navigation operator to make sure data is available

*ngFor="let phone of contact?.phones"

Upvotes: 1

Related Questions