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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With