简体   繁体   English

字符串插值导致Angular 2 App中出现未定义错误

[英]String Interpolation Resulting in Undefined Error in Angular 2 App

I am trying to display some data to the view in my Angular 2 app via string interpolation. 我试图通过字符串插值在Angular 2应用程序中向视图显示一些数据。 For most of the page that's working, but I'm getting an error in this one section that's not making sense to me. 对于大部分正常工作的页面,但是在这一部分我遇到了一个错误,对我来说这没有意义。 It looks like it should work, but I'm getting an 'undefined' error. 看起来应该可以,但是出现了“未定义”错误。

Here's what the data looks like that I'm accessing (note: "contacts" is on the root of the document): 这就是我正在访问的数据(注意:“联系人”位于文档的根目录):

"contacts": [
    {
        "contact": {
            "_id": "111111111",
            "email": [
                "person@email.com"
            ],
            "name": {
                 "first": "Person",
                 "last": "Lastname"
            }
     }
]

I am trying to access the email value in my template using this: 我正在尝试使用以下方法访问模板中的电子邮件值:

First I tried accessing the email address like this: 首先,我尝试像这样访问电子邮件地址:

{{contacts[0]?.contact?.email[0]}}

But got this error: 但是得到了这个错误:

Cannot read property '0' of undefined 无法读取未定义的属性“ 0”

So then I tried a named index: 因此,我尝试了一个命名索引:

{{contacts['contact']?.email[0]}}

This is also not working. 这也不起作用。 I get this error: 我收到此错误:

Cannot read property 'contact' of undefined 无法读取未定义的属性“联系人”

And this is for a record where I know there is a value there. 这是我知道那里有价值的记录。 So I'm unclear why this isn't working? 所以我不清楚为什么这不起作用? Anything look wrong about how I'm accessing the values here? 我在这里如何访问值有什么问题吗?

Contacts is an array , you should access with index Contacts是一个array ,您应该使用index访问

{{contacts[0]?.contact?.email[0]}}

if not use ngFor 如果不使用ngFor

<li *ngFor="let conctact of contacts">
      {{ conctact.email[0]}}
</li>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM