【问题标题】:Displaying an array element in view of angular vs angularjs [duplicate]鉴于angular vs angularjs显示数组元素[重复]
【发布时间】:2017-11-08 14:40:02
【问题描述】:

在 AngularJS 中,当我想显示数组中的特定元素时,在我看来,我会简单地像这样引用它:

<span>{{contact.emails[0].email_address}}</span>

但由于某种原因,在 Angular 中使用相同的设置,我得到了错误:

Runtime Error
Cannot read property 'email_address' of undefined

如果我返回一个包含 emails 数组的联系人对象,我如何引用数组中的第一项?

【问题讨论】:

  • ?操作符试试,可能是第一次渲染模板,数组还是undefined。喜欢,{{ contact?.emails[0]?.email_address }}
  • DV因为缺乏研究,这个问题至少有3个重复

标签: angularjs angular ionic2


【解决方案1】:

试试这个:

<span>{{contact.emails[0]?.email_address}}</span>

这很可能是因为您的电子邮件数组正在异步加载,因此在您的服务返回之前它为空。使用 ?使得它在定义之前不会尝试访问“email_address”属性,因此不会在加载时引发错误。

【讨论】:

  • wdanda,成功了!谢谢你的解释。
  • 很高兴为您提供帮助:)
【解决方案2】:

也许你应该尝试做一个

console.log(contact.emails[0])

因为这个错误意味着你的数组的第一项不存在。

否则,如果它存在,它会这样工作!

<span>{{contact.emails[0].email_address}}</span>

【讨论】:

    【解决方案3】:

    Try this: 
    <ng-template [ngIf]='contact.emails && contact.emails.length > 0'>
      <span>{{contact.emails[0].email_address}}</span>
    </ng-template>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      • 1970-01-01
      • 2018-01-12
      • 2013-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多