Home > database >  Receiving undefined while consoling the zero index value
Receiving undefined while consoling the zero index value

Time:11-02

I try to get the zero index of the array, but I am getting undefined value and I can't bind the value in html using ngFor:

categories: Category[] = [];


  getSubItems(): void {
    this.http
      .get<Category[]>('https://www.themealdb.com/api/json/v1/1/categories.php')
      .subscribe((data) => {
        this.categories = data;
        console.log(this.categories[0]);
      });
  }

HTML

<div  *ngFor="let art of categories">
    <img  style="max-width:300px;" role="button">
    <h1>{{art.strCategory}}</h1>
</div>

Here I am trying to console log the zero index of that array but I'm getting undefined. However, when I console log this.categories I am getting the data.

CodePudding user response:

It seems your problem is fixed doing this:

getSubItems(): void {
 this.http
  .get<{categories: Category[]}>('https://www.themealdb.com/api/json/v1/1/categories.php')
  .subscribe((data) => {
    this.categories = data?.categories;
    console.log(this.categories[0]);
  });
}
  • Related