Angular中ngFor仅重复显示数组最后一个元素问题求助
问题解决:循环请求数据后仅最后一个元素重复显示
问题根源
你代码里的this.api_items是单一变量,循环订阅请求时,每次请求完成都会把它覆盖成当前返回的data.item.current。所有请求结束后,this.api_items最终保留的是最后一次请求的结果,而HTML里所有行都绑定这个变量,自然全部显示最后一条数据。
修复方案
方案1:用数组存储每个ID对应结果
把api_items改成数组,按索引对应存储各请求结果:
组件代码修改
// 先声明api_items为数组类型 api_items: any[] = []; ngAfterViewInit(): void { this.showItems() } showItems(): void { const id: any[] = []; this.idFromList.forEach((val: any) => id.push(val.nativeElement.innerText)); for(let i = 0; i < id.length; i++) { this.ItemService.showItems(id[i]).subscribe(data => { // 按索引给数组对应位置赋值 this.api_items[i] = data.item.current; console.log(this.api_items[i]); }); } }
HTML代码修改
循环时获取当前行索引,对应绑定数组元素:
<table> <thead> <tr> <td>Name</td> <td>Price</td> </tr> </thead> <tbody> <!-- 添加let i = index获取当前行索引 --> <tr *ngFor="let item of items | filter: searchQuery; let i = index" > <td > <a href="" #btn>{{item.id}}</a> <a href="">{{ item.name }}</a> </td> <!-- 绑定对应索引的api_items元素 --> <td *ngFor="let api_item of api_items[i] | keyvalue"> {{ api_item.value }} </td> </tr> </tbody> </table>
方案2:用forkJoin并行请求(更推荐的RxJS写法)
如果所有请求可并行发起,用forkJoin一次性获取所有结果,避免循环订阅:
组件代码修改
import { forkJoin } from 'rxjs'; api_items: any[] = []; ngAfterViewInit(): void { this.showItems() } showItems(): void { // 先提取所有ID const idList: string[] = this.idFromList.map(val => val.nativeElement.innerText); // 生成所有请求的Observable数组 const requests$ = idList.map(id => this.ItemService.showItems(id)); forkJoin(requests$).subscribe(results => { // 把每个请求结果对应存入数组 this.api_items = results.map(res => res.item.current); }); }
HTML部分和方案1一致,用索引绑定对应元素即可。
额外提示
- 避免在循环内直接订阅Observable,容易引发内存泄漏,优先用
forkJoin/concatMap等RxJS操作符管理异步流 - 可添加加载状态,避免请求未完成时页面显示空内容
- 若
idFromList是通过@ViewChildren获取,确保ngAfterViewInit钩子触发时已正确获取到DOM元素
内容的提问来源于stack exchange,提问作者letmeusedarkmode
相关产品推荐
相关产品推荐

