-1

I retrieve my JSON file from this URL [http://www.bcetupes.info/wp-json/wp/v2/posts?page=1&_embed]

In my template, I have this code

  <p *ngFor="let news of newsObj">
      {{news._embedded["wp:featuredmedia"][0]['id']}}
  </p>

The problem is that in my JSON file "wp:featuredmedia" can be missing. I have tried several things for example {{news._embedded.featuredmedia?[0]?.id}} but I don't know how to fix this problem in the template.

I need test if "wp:featuredmedia" exists in my object...

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
kazou
  • 77
  • 2
  • 11

1 Answers1

1

You need to make sure that the object you are accessing exists before you access it or you will encounter a run time error. Here is one way to handle it using *ngIf:

<p *ngFor="let news of newsObj">
   <span *ngIf="news._embedded["wp:featuredmedia"] !== undefined">
     {{news._embedded["wp:featuredmedia"][0]['id']}}
   </span>
</p>
silentsod
  • 8,165
  • 42
  • 40
Yoav Schniederman
  • 5,253
  • 3
  • 28
  • 32