在打字稿中循环遍历formdata

时间:2019-05-18 21:21:55

标签: angular typescript loops for-loop multipartform-data

我正在尝试遍历formdata,我读了好几次书,我应该能够在for ... of ...循环中使用FormData,但是当我尝试时,出现错误:

Type 'FormData' is not an array type or a string type

我的代码:

export class NewsCreationComponent implements OnInit {

  fileToUpload: File = null;
  uploadImages = new FormData();

...

  handleFile(event) {
    this.fileToUpload = event.target.files;
    this.uploadImages.append(this.fileToUpload.name, this.fileToUpload);
  }

  save() {
    for (let up of this.uploadImages) {
      this.imageService.createImage(up)
      });
}

我在做什么错?

2 个答案:

答案 0 :(得分:1)

将FormData初始化uploadImages = new FormData();移动到ngOnInit()生命周期挂钩,因此可以确保在调用save()函数时定义了它。

答案 1 :(得分:0)

FormData是不可迭代的,如果要遍历FormData键,请使用entries方法

   for (let [key, file] of this.uploadImages.entries()) {
      this.imageService.createImage(file)
   });

values方法

   for (let file of this.uploadImages.values()) {
      this.imageService.createImage(file)
   });