angular - NgFor 仅支持绑定到 Iterables,例如 Arrays。角度错误,无法将 GET API 用于前端 HTML
问题描述
我的 component.ts 文件
export class TeamComponent implements OnInit {
teams: any;
constructor(private http: HttpClient) { }
ngOnInit(): void {
let resp = this.http.get("https://api.squiggle.com.au/?q=teams");
resp.subscribe((data) => this.teams = data);
}
}
我的 HTML 文件
<section class="teams container text-center">
<h1>List of Teams</h1>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Abbrev</th>
<th scope="col">Logo</th>
<th scope="col">Team Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let team of teams">
<td>{{team.id}}</td>
<td>{{team.abbrev}}</td>
<td>{{team.logo}}</td>
<td>{{team.name}}</td>
</tr>
</tbody>
</table>
</section>
我可以通过 HTTP 客户端控制台记录我的团队数据,但是当我尝试通过声明 team: any; 在 HTML 上显示它时 控制台抛出错误“找不到类型为‘object’的不同支持对象‘[object Object]’。NgFor 仅支持绑定到 Iterables,例如数组。”
解决方案
您可以执行以下操作,
this.httpClient.get("https://api.squiggle.com.au/?q=teams").subscribe((res: any) => {
this.responseData = JSON.parse(JSON.stringify(res))["teams"];
},
err => {
console.log(err);
},
() => {
console.log(this.responseData);
}
)
}
您现在应该能够使用 *ngFor 指令迭代 responseData。
此外,您可以将 responseData 声明为responseData: any
推荐阅读
- python - 试图通过政府网站上的数十万个 pdf 进行网络抓取。想要尽快完成
- reactjs - 在 React 中的数字输入上使用 toFloat 和 setState
- java - Java:将克隆作为函数参数而不是引用传递
- python - 使用正则表达式 pandas 改变年龄
- linux-kernel - PCI 驱动程序失败:在设备上检测到 PCI 总线错误
- angular - 角度获取 web api 数据(在浏览器网络选项卡中,它以 200 ok 响应获取数据)但数据不显示
- javascript - Webpack Loaders - 在 loader 中创建和写入文件
- python - Sklearn 分类器无法使用 Gensim Word2Vec 数据进行训练
- excel - VBA将显示的单元格时间转换为变量分配
- jquery - ASP.NET 的 AJAX 发布问题