无法访问对象

时间:2018-02-16 01:44:36

标签: angular

我是Angular的新手(从AngularJS转来)

我正在调用一个api,它返回一个带有子文档(数组)的对象。

从api返回的对象基本上是:

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

在我的html中,我可以致电{{contact.first_name}}

但如果我尝试像这样做'* ngFor':

*ngFor="let phone of contact.phones"

我收到编译错误,说它找不到'未定义'的'手机'。

这对我不起作用,因为我知道'contact'没有未定义,我可以看到返回完整的对象。

我错过了什么?

1 个答案:

答案 0 :(得分:1)

由于您通过异步调用从api请求,您需要使用* ngIf或使用安全导航操作符来确保数据可用

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