如何遍历类型化数组



我的应用程序Angular中有以下类模型:

export class IItemsModel {
public description: string;
public itemDetail: IItemDetailModel;
public itemCategories: IItemCategoriesModel[];  // array of IItemCategoriesModel
}
export class IItemCategoriesModel {
public id: string | number;
public description: string;
}

我的控制器:

itemModel: IItemsModel;
selectedCategories: any[] = [];
ngOnInit() {
this.itemModel = new IItemsModel();
this.itemModel.itemCategories = [];
}
onSubmit(form: NgForm) {
// here I format the data
}

在模板中,我有一个多选,其中我用所选类别的id填充array

[25, 38]  // selectedCategories

问题,我使用ngModel将表单与控制器链接,但要将预先填充的数据发送到API,我必须将id格式化为模型格式,即:

{
...,
itemDetail: 'something',
itemCategories: [
{ id: any Id },
{ id: other Id }
]
}

我尝试用onSubmit()方法将数据格式化如下:

for(let i=0; i<this.selectedCategories.length; i++) {
this.itemModel.itemCategories[i].id = this.selectedCategories[i];
}

但我得到了错误:

TypeError:无法设置undefined@undefined:undefined 的属性"id">

如何格式化itemCategories以便能够将数据正确发送到API?

使用forEach进行迭代,而不是使用for循环。

this.selectedCategories.forEach(f => {
this.itemModel.itemCategories.push({ id: f, description: '' })
});

由于selectedCategories对象是一个数字数组,所以它没有id属性。这就是为什么会出现错误。

工作演示在StackBlitz。

单击按钮并检查控制台日志

最新更新