问题
I am trying to access the category slug for a product in ionic using the WordPress rest API. This seems to work fine on one page as <h3 class="product-name uppercase">{{productdetail?.categories[0].slug}}</h3>
however this does not seems to work when i try implementing the same using for loop in angular on another page
<div class="width50" *ngFor="let object of dataList">
<img src="{{object.images[0].src}}" width="150" (click)="navigateToPage(object.id)" />
<h3 class="product-name uppercase" text-nowrap>{{object?.categories[0].slug}}</h3>
</div>
it gives an error as v.context.$implicit.categories[0] is undefined
however on same page the code for image source seems to work fine.
回答1:
According to the docs
The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null.
This way if write
obj?.foo
angular will transform it to the following expression.
obj == null ? null : obj.foo
so if the obj
is empty value then you won't see any of errors.
In your case you can use the expresion
object?.categories[0]?.slug
that will be transformed to
object == null ? null : object.categories[0] == null ? null : object.categories[0].slug;
Safe navigation operator is helpful if you don't know whether your object contains any value or not, or you load data asynchronously and your object is undefined
at first time.
来源:https://stackoverflow.com/questions/44944637/v-context-implicit-categories0-is-undefined-error-in-ionic-3