【问题标题】:Can't display target array within object using *ngFor无法使用 *ngFor 在对象内显示目标数组
【发布时间】:2018-04-01 03:44:46
【问题描述】:

我有一个 Angular 应用程序,其中一个视图显示的是联系人电话号码列表。

我的对象示例:

联系人:{ 名称:“萨姆·史密斯”, 电话:[ {电话类型:'家',电话号码:'222-222-2222'}, {电话类型:'手机',电话号码:'333-333-3333'} ] }

在我的 html 中,我可以使用 {{contact.name}}

访问联系人姓名

但是如果我尝试像这样使用 *ngFor 循环电话数组:

<div *ngFor="let phone of contact.phones">{{phone.phone_number}}</div>

我明白了:

“ContactEditPage.html:61 ERROR TypeError: Cannot read property 'phones' of undefined”。

所以我知道对象正在被返回,但为什么我不能查看手机数组?

【问题讨论】:

  • 这很可能是因为您正在异步加载数据,您应该将联系人初始化为对象{}

标签: angular


【解决方案1】:

您应该使用安全导航运算符来检查值是否存在,因为您的 api 调用异步返回数据

<div *ngFor="let phone of contact?.phones">{{phone?.phone_number}}</div>

【讨论】:

  • 是吗?使调用异步?
  • 不,在您从 api 获取数据之前,它不会抛出未定义的错误
  • 做到了。谢谢!!
猜你喜欢
  • 2018-08-13
  • 2022-07-07
  • 1970-01-01
  • 2017-04-07
  • 2023-03-15
  • 2018-02-17
  • 2017-12-13
  • 2019-11-10
  • 2018-03-20
相关资源
最近更新 更多