Angular重复对象问题求助:提交数据至Web API出现重复条目
重复数据问题排查与修复
问题场景
有两行数据,每行对应一个带索引的按钮。点击按钮弹出含输入框的对话框,提交输入内容后,数据通过result赋值给变量,但保存到Web API时出现重复数据——本该保存两组不同数据,结果最终只保存了第二组数据两次。
输入数据
Index(0) 0: {ArrayList: 0, itemName: 'TEST001A'} 1: {ArrayList: 0, itemName: 'TEST001B'} length: 2 [[Prototype]]: Array(0) Index(1) 0: {ArrayList: 576, itemName: 'TEST002A'} 1: {ArrayList: 576, itemName: 'TEST002B'} length: 2 [[Prototype]]: Array(0)
保存后异常结果
TEST002A TEST002B TEST002A TEST002B
相关代码
对话框关闭后获取数据的代码
dialogRef.afterClosed().subscribe((result) => { this.names= result })
提交数据的代码
onSave(){ for(const details of this.fg.value?.displayArray){ this.service.pD(details).subscribe((resp) =>{ this.test001 = resp.id; for(let i = 0; i < this.names.length; i++){ this.names[i].ArrayList = this.test001 this.service.pS(this.names[i]).subscribe((res)=>{ console.log(res) }) } }) } }
问题根源
- 全局变量被覆盖:
this.names是全局变量,处理第二行数据时,它会被替换成第二组的TEST002A/B。而循环里的pD请求是异步的,第一个请求还没执行完内部的pS,第二个循环就已经把this.names覆盖了,导致第一个循环最终用的是第二组数据。 - 异步时序混乱:
subscribe是异步执行的,遍历displayArray时会先触发所有pD请求,this.test001和this.names是共享变量,后面的请求会覆盖前面的值,最终所有pS请求都用了最后一次的变量值。
修复方案
核心是让每组数据的names和对应的resp.id绑定,避免变量被覆盖。需要将每行的names单独存储,而不是用全局变量覆盖:
1. 对话框关闭时存储对应行的names
打开对话框时传递当前行的索引,关闭后将结果存入对应位置的数组:
// 打开对话框时记录当前行索引index dialogRef.afterClosed().subscribe((result) => { this.rowNames[index] = result; // 用数组存储每行的names,比如this.rowNames = [] })
2. 提交时使用对应行的names数据
在onSave循环中,获取当前行对应的names,避免使用被覆盖的全局变量:
onSave(){ this.fg.value?.displayArray.forEach((details, index) => { this.service.pD(details).subscribe((resp) =>{ const currentId = resp.id; const currentNames = this.rowNames[index]; // 获取当前行对应的names if(currentNames){ currentNames.forEach(item => { item.ArrayList = currentId; this.service.pS(item).subscribe(res => { console.log(res); }); }); } }); }); }
内容的提问来源于stack exchange,提问作者Mitch
相关产品推荐
相关产品推荐

