简体   繁体   English

如何遍历类型化数组?

[英]How to traverse a typed array?

I have the following class model in my application Angular:我的应用程序 Angular 中有以下 class model:

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;
}

And my Controller:还有我的 Controller:

itemModel: IItemsModel;
selectedCategories: any[] = [];

ngOnInit() {
  this.itemModel = new IItemsModel();
  this.itemModel.itemCategories = [];
}

onSubmit(form: NgForm) {
  // here I format the data
}

In the template I have a multiple select where I fill an array with the id's of the chosen categories.在模板中,我有多个 select 在其中我用所选类别的 id 填充array

[25, 38]  // selectedCategories

Problem, I'm using ngModel to link the form with the controler, but to send the pre-filled data to the API, I have to format the id's to the model format, that is:问题,我正在使用ngModel将表单与控制器链接,但是要将预填充的数据发送到 API,我必须将 id 格式化为 model 格式,即:

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

I try to format the data as follows in the onSubmit() method:我尝试在onSubmit()方法中按如下方式格式化数据:

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

But I get the error:但我得到了错误:

TypeError: Cannot set property 'id' of undefined @ undefined:undefined TypeError:无法设置未定义@未定义的属性“id”:未定义

How could you be formatting the itemCategories to be able to send the data correctly to the API?您如何格式化 itemCategories 才能将数据正确发送到 API?

Use forEach to iterate instead of for loop.使用forEach迭代而不是for循环。

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

Since your selectedCategories object is an array of numbers, it doesn't have id property in it.由于您selectedCategories object 是一个数字数组,因此它没有id属性。 That's why you're getting errors.这就是为什么你会出错。

Working demo at StackBlitz .StackBlitz工作演示

Click the button and check the console log.单击按钮并检查控制台日志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM