Cannot read property of undefined angular2 ngif

2019-02-23 06:11发布

I am now able to get the object in the view however I cannot run an if statement. Per previous answer this is how I am bringing in the object.

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;
  }
}

I am trying to run but get cannot get property vegetable.

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

The error is

Cannot read property 'vegtable' of undefined

2条回答
混吃等死
2楼-- · 2019-02-23 06:26

The cart object is null until the service getPosts$ returns (callback). Therefore, the code *ngIf="cart.vegetable ... is equal to *ngIf="null.vegetable ... until that happens. That is what is happening.

What you could do is put a DOM element with *ngIf="cart" containing the other *ngIf. For example:

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

*Edit: As it is said in the next answer, a good alternative (and good practice) is the following:

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

查看更多
【Aperson】
3楼-- · 2019-02-23 06:39

Use the safe-navigation operator to guard against null or undefined for async fetched data:

<h2 *ngIf="cart?.vegetable == 'carrot' ">{{cart.vegetable}}</h2>
查看更多
登录 后发表回答