angular2:错误:TypeError:无法读取未定义的属性“ ...” [英] angular2: Error: TypeError: Cannot read property '...' of undefined

查看:154
本文介绍了angular2:错误:TypeError:无法读取未定义的属性“ ...”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已附上我的angular2代码段的小栓。我想从JSON打印一个字段,但由于最初我的Object为null,并且无法通过Promise进行填充,因此无法打印。

I have attached the plunker of my angular2 code piece. I want to print a field from my JSON but unable to print that as initially my Object is null and it is being populated via a Promise.

这是我的组件文件

import {Component, NgModule, OnInit} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

class MyData {
  xyz : MySubData;
}

class MySubData {
  name : string;
} 
@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>

      {{abc.xyz.name}}
    </div>
  `,
})
export class App implements OnInit {
  abc : MyData = null;
  constructor() {
    this.name = 'Angular2'
  }

  ngOnInit() {
    setTimeout(() => {
      this.abc = new MyData();
      this.abc.xyz = new MySubData();
      this.abc.xyz.name = "Binita";
    }, 2000);
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

当我删除行 {{abc.xyz.name}} 在我的模板中运行正常。

When I am removing the line {{abc.xyz.name}} from my template it is running fine.

我已经使用了set在代码中超时,因为我正在从Promise中获取数据(即异步调用)。

I have use set time out in my code because I am getting my data from Promise (i.e asynchronous call).

最初我可以理解为 abc null ,我的代码无法找到abc.xyz.name。但是我不想检查任何条件。因为我在JSON中有几个属性,所以如果条件满足,则不可能为每个属性写。

I can understand initially as abc is null, my code is unable to find abc.xyz.name. But I don't want to put any if condition to check. Because I have several property inside a JSON and it is not possible for each property to write if condition.

angularjs 1的早期版本,如果abc为null,那么它将自动替换它与空白字符串。我想在angular2中做同样的事情。请提出建议。

Earlier in angularjs 1 if abc is null then it would automatically replace it with blank string. I want to do the same thing in angular2. Please suggest.

下面是the车手

https://plnkr.co/edit/u1NqNF0penz7OS55QmoU?p=preview

推荐答案

这是因为在模板渲染时未定义 abc 。您可以使用安全的导航运算符()来保护模板,直到HTTP调用完成:

That's because abc is undefined at the moment of the template rendering. You can use safe navigation operator (?) to "protect" template until HTTP call is completed:

{{abc?.xyz?.name}}

您可以阅读有关安全导航操作员的详细信息,请此处

You can read more about safe navigation operator here.

更新:

不能在数组中使用安全的导航运算符,您必须利用 NgIf 指令来克服此问题:

Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf directive to overcome this problem:

<div *ngIf="arr && arr.length > 0">
    {{arr[0].name}}
</div>

了解有关 NgIf 指令此处

这篇关于angular2:错误:TypeError:无法读取未定义的属性“ ...”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆