angular - 为什么 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])});
}
解决方案
您的服务应该从响应中返回数组。假设您的响应看起来像您显示的返回数组:
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])});
推荐阅读
- sabre - 是否可以在检索 PNR 响应中对航段进行分组?
- python - 如何在 python 中使用 glob.glob 从具有不同名称的多个输入文本文件中写入多个输出文本文件?
- vba - VBA 将动态范围从一个工作表复制/粘贴到另一个工作表
- swift - 添加约束混乱的视图
- javascript - Vue js 2.5 在 IOS 9 下的 safari 中不工作
- python-3.x - 如何将在线数据集用于分段对象
- sql - 没有为“TableA”的 column1 指定列名
- python - Readlines.() 重复相同的答案?
- c# - WCF 命名管道地址AlreadyInUseException
- firebase - 电话号码的 Firestore 安全规则问题