Angular Table 删除操作异常:删任意项变删首项、刷新后数据恢复问题排查
问题根因
1. 任意删除都删第一个元素的原因
你在HTML中调用deleteWorkItem方法时仅传入了row参数,方法定义中第二个入参index没有接收传值,默认是undefined。执行数组splice(undefined, 1)时,JS会自动将第一个参数转为数值0,所以永远会删除数组的第一个元素。
2. 刷新后删除元素复现的原因
有两个常见诱因:
- 你把本地数据源修改的逻辑写在了接口请求的外部,不等后端删除接口返回结果就直接改了本地数据,如果接口请求失败、参数错误或者后端逻辑异常,实际并没有完成数据删除,刷新页面重新拉取后端全量数据时,被删除的元素自然会重新出现
- 删除接口调用方式不匹配:通常删除操作对应后端
DELETE类型接口,你用update方法(一般对应PUT/POST)调用可能不符合后端接口要求,导致删除请求没有被后端正确处理
修复方案
步骤1:修改HTML代码,补充index传参
首先在mat-table的行定义处声明index变量,再传入删除方法:
<!-- 行定义部分新增index变量声明 --> <mat-row *matRowDef="let row; columns: displayedColumns; let i = index;"></mat-row> <!-- 删除按钮点击事件补全参数 --> <button mat-icon-button> <mat-icon (click)="deleteWorkItem(row, i)">block</mat-icon> </button>
步骤2:修改TS代码,调整逻辑顺序并补全校验
将本地数据修改逻辑移到接口请求成功的回调中,新增参数校验和错误处理,同时确认接口调用方式和后端要求匹配:
deleteWorkItem(row: IProduct, index: number) { // 前置参数校验,避免无效请求 if (!this.SupplierId || !row?.ProductId) { this._customNotificationService.Show('参数缺失,删除失败', 'Tamam', 3); return; } const supplierProduct: ISupplierProduct = { Supplier: { SupplierId: this.SupplierId }, Product: { ProductId: row.ProductId } }; this.confirmDialogRef = this._dialog.open(FuseConfirmDialogComponent, { disableClose: false }); this.confirmDialogRef.componentInstance.confirmMessage = 'Ürünü silmek istiyor musunuz?'; this.confirmDialogRef.afterClosed().subscribe(result => { if (!result) return; // 如果后端删除接口要求DELETE请求,替换_service.update为对应delete方法 this._service.update('Supplier/DeleteSupplierProduct', supplierProduct).subscribe({ next: () => { this._customNotificationService.Show('Ürün silindi', 'Tamam', 2); // 接口返回成功后再修改本地数据 const tempData = [...this.dataSource.data]; tempData.splice(index, 1); this.dataSource = new MatTableDataSource(tempData); this.EditIndex = undefined; this._products = this.dataSource.data; this.ProductChange.emit(this._products); }, error: (err) => { console.error('删除接口调用失败', err); this._customNotificationService.Show('Ürün silme başarısız oldu', 'Tamam', 3); } }); }); }
额外检查项
- 确认后端
Supplier/DeleteSupplierProduct接口的请求方式、参数格式要求,确保前端传参符合规则 - 确认页面初始化拉取产品列表的接口没有使用本地缓存,每次刷新都会拉取后端最新数据
内容的提问来源于stack exchange,提问作者Hectic Platypus
相关产品推荐
相关产品推荐

