我现在可以在 View 中获取对象,但是我无法运行 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;
}
}
我正在尝试运行,但无法获取属性蔬菜。
<h2 *ngIf="cart">{{cart.vegetable}}</h2>
<h2 *ngIf="cart.vegetable == 'carrot' ">{{cart.vegetable}}</h2>
错误是
Cannot read property 'vegtable' of undefined
最佳答案
cart
在服务 getPosts$
之前对象为空返回(回调)。因此,代码 *ngIf="cart.vegetable ...
等于*ngIf="null.vegetable ...
直到那发生。这就是正在发生的事情。
你可以做的是用 *ngIf="cart"
放置一个 DOM 元素包含另一个*ngIf
.例如:
<div *ngIf="cart">
<h2 *ngIf="cart.vegetable == 'carrot' ">{{cart.vegetable}}</h2>
</div>
*编辑:正如下一个答案中所说,一个很好的选择(和良好做法)如下:
<h2 *ngIf="cart?.vegetable == 'carrot' ">{{cart.vegetable}}</h2>
关于javascript - 无法读取未定义的 angular2 ngif 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41985595/