首页 > 解决方案 > 为什么 ngFor 循环遍历 JSON 数组但返回空属性值?

问题描述

一直在使用 ngFor 循环一个 json 数组,但它返回空。

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

返回的数组是:

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

服务

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

组件.ts

HeroesWebAPI:  any[]= [];

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

标签: angulartypescriptobservable

解决方案


您的服务应该从响应中返回数组。假设您的响应看起来像您显示的返回数组:

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

然后稍后在你的 getHeroes

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

推荐阅读