首页 > 解决方案 > 如何遍历类型化数组?

问题描述

我的应用程序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
}

在模板中,我有一个多项选择,我在其中填写array所选类别的 ID。

[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:无法设置未定义@未定义的属性“id”:未定义

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

标签: javascriptangulartypescript

解决方案


用于forEach迭代而不是for循环。

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

由于您的selectedCategories对象是一个数字数组,因此它没有id属性。这就是为什么你会出错。

StackBlitz工作演示

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


推荐阅读