【问题标题】:Can't access an array within my object无法访问我的对象中的数组
【发布时间】:2018-02-16 01:44:35
【问题描述】:

我是 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"

我收到一个编译错误,说它找不到“未定义”的“电话”。

这对我来说没有意义,因为我知道“联系人”不是未定义的,我可以看到返回了完整的对象。

我错过了什么?

【问题讨论】:

    标签: angular


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,Sajeetharan。我在提交帖子后两分钟就想通了。但这可能对其他人有所帮助。等待期结束后,我会立即接受您的回复。再次感谢!
    猜你喜欢
    • 2017-08-13
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 2016-07-09
    • 2018-01-03
    相关资源
    最近更新 更多