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 servicegetPosts$
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:*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>
Use the safe-navigation operator to guard against
null
orundefined
for async fetched data: