试图在数组上循环并显示结果,但只显示最后一个元素多次。
这是我的密码。
提出获取请求。
showItems(id: any): Observable<any> {
return this.http.get(`${this.url}${id}`)
}
控制台日志在这里运行良好,我可以看到预期的结果。
ngAfterViewInit(): void {
this.showItems()
}
showItems(): void {
const id: any = []
this.idFromList.forEach((val: any) => id.push(val.nativeElement.innerText))
for(let i = 0; id.length > i; i++) {
this.ItemService.showItems(id[i]).subscribe(data => {this.api_items = data.item.current
console.log(this.api_items)});
}
}
HTML
<table>
<thead>
<tr>
<td>Name</td>
<td>Price</td>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of items | filter: searchQuery" >
<td >
<a href="" #btn>{{item.id}}</a>
<a href="">{{ item.name }}</a>
</td>
<td *ngFor="let api_item of api_items | keyvalue">
{{ api_item.value }}
</td>
</tr>
</tbody>
</table>
尝试使用伪造的JSON服务器,结果相同。
1(快速回答
推送数组中的项目而不是替换其值:
api_items = [];
this.ItemService.showItems(id[i]).subscribe(data => {
this.api_items.push(data.item.current);
});
2(完整答案
- 正如@MoxxiManagarm所说,您将在
for
循环的每次迭代中替换api_items
值 - 您可能需要检查&使用RxJS以更干净的方式处理多个可观察性:例如,通过生成一个Observable数组来一起解析它们
3(资源;您可能想要查看的有用链接以获取更多信息
https://www.learnrxjs.io/