問(wèn)題描述
我現(xiàn)在可以在視圖中獲取對(duì)象,但是我無(wú)法運(yùn)行 if 語(yǔ)句.根據(jù)之前的回答,這就是我引入對(duì)象的方式.
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;
}
}
我正在嘗試運(yùn)行,但無(wú)法獲得屬性蔬菜.
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>
錯(cuò)誤是
無(wú)法讀取未定義的屬性vegtable"
Cannot read property 'vegtable' of undefined
推薦答案
cart
對(duì)象為空,直到服務(wù) getPosts$
返回(回調(diào)).因此,代碼 *ngIf="cart.vegetable ...
等于 *ngIf="null.vegetable ...
直到發(fā)生這種情況.這就是正在發(fā)生的事情.
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.
您可以做的是放置一個(gè)帶有 *ngIf="cart"
的 DOM 元素,其中包含另一個(gè) *ngIf
.例如:
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>
*正如在下一個(gè)答案中所說(shuō),一個(gè)很好的選擇(和良好的做法)如下:
* 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>
這篇關(guān)于無(wú)法讀取未定義 angular2 ngif 的屬性的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!