0

I made an Ionic WordPress app that gives me an error every time a post is published without a featured photo.
What I'm trying to do is filter out those posts that doesn't have a photo but I don't know how to use if/else condition in Ionic.
This is the code for home.html

<ion-card *ngFor="let item of items">
    <img src="{{item._embedded['wp:featuredmedia'][0].media_details.sizes.thumbnail.source_url}}"/>
    <ion-card-content>
    ...
    </ion-card-content>
</ion-card>

1 Answer 1

1

If you're trying to remove items from items that don't have a thumbnail, it's better to do it on the backend when you get them.

this.items = this.items.filter(function(item) {
  return (item && 
          item._embedded &&
          item._embedded['wp:featuredmedia'] &&
          item._embedded['wp:featuredmedia'][0] &&
          item._embedded['wp:featuredmedia'][0].media_details &&
          item._embedded['wp:featuredmedia'][0].media_details.sizes &&
          item._embedded['wp:featuredmedia'][0].media_details.sizes.thumbnail &&
          item._embedded['wp:featuredmedia'][0].media_details.sizes.thumbnail.source_url);
});

If you want to get every item, thumbnail or no, but hide the thumbnail if it doesn't exist, use *ngIf on your img tag.

<ion-card *ngFor="let item of items">
  <img *ngIf="item && 
              item._embedded &&
              item._embedded['wp:featuredmedia'] &&
              item._embedded['wp:featuredmedia'][0] &&
              item._embedded['wp:featuredmedia'][0].media_details &&
              item._embedded['wp:featuredmedia'][0].media_details.sizes &&
              item._embedded['wp:featuredmedia'][0].media_details.sizes.thumbnail &&
              item._embedded['wp:featuredmedia'][0].media_details.sizes.thumbnail.source_url"
       src="{{item._embedded['wp:featuredmedia'][0].media_details.sizes.thumbnail.source_url}}"/>
</ion-card>

Note: The reason you should check each layer of the object is because if any one of them is missing, you'll get a TypeError saying "could not find property X of undefined".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.