Angular11中如何将Mat-Dialog传递的数据转换为Goods类数组对象
问题原因及解决方法
核心问题点
- 传递给MatDialog的初始数据类型错误:你定义的
goodsSelect是可选类型? Goods[],默认值为undefined,首次打开弹窗时传递的是undefined而非数组类型,即便后续用as Goods[]强转,变量本质仍然不是数组,调用filter/forEach等数组方法自然会报错。 - 属性名拼写不匹配:你定义的
Goods接口字段为goodsId/goodsCode/goodsName,但后续代码中用的是goodId/goodCode/goodName1,字段名不一致导致无法读取属性值。 dataSource未赋值就遍历:你初始化dataSource时传入的是空数组,还没请求后端商品列表赋值就直接遍历,自然没有日志输出也没有匹配结果。
修复步骤
1. 修正父组件初始值
把PromotionAddComponent里的goodsSelect初始化改为空数组,保证传递给弹窗的永远是数组类型:
export class PromotionAddComponent implements OnInit { // 改为非可选类型,初始为空数组 goodsSelect: Goods[] = []; openDialog() { const dialogConfig = new MatDialogConfig(); dialogConfig.data = this.goodsSelect; const dialogRef = this.dialog.open(ProductListComponent, dialogConfig); dialogRef.afterClosed().subscribe(data => { // 加判断,只有返回数组的时候才赋值 if(Array.isArray(data)) { this.goodsSelect = data; } }); } }
2. 修正弹窗组件的字段拼写、数据源赋值逻辑
先请求商品列表赋值给dataSource,再做选中项匹配,同时加数组类型判断兜底:
export class ProductListComponent implements OnInit { public allGoods?: Goods[]; public selectedItem?: Goods[]; displayedColumns: string[] = ['select', 'goodsCateName', 'goodsGroupName', 'goodsCode', 'goodsName', 'goodsUnitName']; dataSource = new MatTableDataSource<Goods>([]); selection = new SelectionModel<Goods>(true, []); constructor( private goodsService: GoodsService, private dialogRef: MatDialogRef<ProductListComponent>, // 直接定义为Goods数组类型 @Inject(MAT_DIALOG_DATA) private data: Goods[]) { } ngOnInit(): void { this.selectedItem = this.data; // 先判断是否是数组,避免报错 if(!Array.isArray(this.selectedItem)) { this.selectedItem = []; } // 先请求所有商品数据,赋值后再做匹配 this.goodsService.getGoodsList().subscribe(res => { this.allGoods = res; this.dataSource.data = res; // 数据源赋值后再匹配选中项 this.dataSource.data.forEach(item => { // 修正字段拼写为goodsId const matched = this.selectedItem!.filter(e => e.goodsId === item.goodsId); if(matched.length > 0) { this.selection.select(item); } }) }) } }
内容的提问来源于stack exchange,提问作者Kantrakorn J
相关产品推荐
相关产品推荐

