afaaqa dabookick
afaaqa dabookick

Reputation: 97

Why the ngFor is looping through a JSON array but returns empty property values?

Been looping through a json array using ngFor but it returns empty.

<ul>
    <li *ngFor="let h of HeroesWebAPI" (click)= "OnSelectedFunc(h)"> {{h.Name}} </li>
</ul>

returned arary is:

[{"Id":1,"Name":"John-1"},{"Id":2,"Name":"John-2"}]

Service

  getHeroesFromWebAPI(): Observable<any>
  {    
    return this.http.get<any>("https://localhost:44320/api/values").pipe(
      map(res => JSON.stringify(res))
    );
  }

Component.ts

HeroesWebAPI:  any[]= [];

getHeroes(): void
     {
        console.log("getHeroes called");
        this.heroService.getHeroesFromWebAPI().subscribe( r => {this.HeroesWebAPI= [r]; 
          console.log("Final hit:"+  [this.HeroesWebAPI])});  
     }

Upvotes: 0

Views: 170

Answers (2)

Alberto Rivera
Alberto Rivera

Reputation: 3752

Your service should return the array from the response. Assuming your response looks like the returned array you showed:

getHeroesFromWebAPI(): Observable<any>
  {    
    return this.http.get<any>("https://localhost:44320/api/values");
  }

Then later in your getHeroes

this.heroService.getHeroesFromWebAPI().subscribe( r => {this.HeroesWebAPI=r; 
          console.log("Final hit:"+  [this.HeroesWebAPI])});

Upvotes: 1

Awabil George
Awabil George

Reputation: 310

<ul  *ngFor="let h of HeroesWebAPI" >
    <li(click)= "OnSelectedFunc(h.id,h.Name)"> {{h.Name}} </li>
</ul>

OnSelectedFunc(id, name) {
  console.log(`ID:${id},Name:${name}`)
}

Upvotes: 0

Related Questions