无法读取undefined angular2 ngif的属性

Mat*_*att 7 javascript ionic-framework ionic2 angular

我现在能够在视图中获取对象但是我无法运行if语句.根据之前的回答,这就是我引入对象的方式.

public getPosts$(category, limit) {
  return this.cartService.getPosts(category, limit).map(response => {
    return response && response.data && response.data.children;
  };
}

ngOnInit() {
  this.getPosts$(this.category, this.limit).subscribe(cart => {
    this.cart = cart;
  }
}
Run Code Online (Sandbox Code Playgroud)

我想跑,但得不到财产蔬菜.

<h2 *ngIf="cart">{{cart.vegetable}}</h2>
<h2 *ngIf="cart.vegetable == 'carrot' ">{{cart.vegetable}}</h2>
Run Code Online (Sandbox Code Playgroud)

错误是

无法读取未定义的属性'vegtable'

Cod*_*cus 14

cart在服务getPosts$返回(回调)之前,该对象为null .因此,代码*ngIf="cart.vegetable ...等于*ngIf="null.vegetable ...直到发生.这就是发生的事情.

你可以做的是放一个*ngIf="cart"包含另一个的DOM元素*ngIf.例如:

<div *ngIf="cart">
    <h2 *ngIf="cart.vegetable == 'carrot' ">{{cart.vegetable}}</h2>
</div>
Run Code Online (Sandbox Code Playgroud)

*编辑:正如在下一个答案中所说,一个很好的选择(和良好做法)如下:

<h2 *ngIf="cart?.vegetable == 'carrot' ">{{cart.vegetable}}</h2>


Gün*_*uer 13

使用安全导航操作,以防止nullundefined用于异步获取的数据:

<h2 *ngIf="cart?.vegetable == 'carrot' ">{{cart.vegetable}}</h2>
Run Code Online (Sandbox Code Playgroud)