简体   繁体   中英

Cannot read property of undefined angular2 ngif

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

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>

使用安全导航运算符来防止异步获取的数据为nullundefined

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

I used {{ }} while they are not needed. Getting rid of them fixed it for me.

So this

<li *ngIf="{{house}}">

Should be

<li *ngIf="house">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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