提问者:小点点

在AJAX调用的成功响应中推送数组中的数据会导致多次附加最后的数据


我试图在文件上传成功响应时将数据附加到数组中。在循环控制台中给出了正确的输出,但结果数组由复制的数据组成(最后的数据重复n次)

 data : consists of multiple file data that has to be uploaded

例子:

FileList{0: File,1:File,长度:2}0:File{name:"demoform1.pdf",lastModify:1565685422300,lastModifiedDate:Tue Aug 13 2019 14:07:02GMT0530(印度标准时间),webkitRelativePath:"",size:20061,…}1:File{name:"dummy.pdf",lastModify:1565260694049,lastModifiedDate:Thu Aug 08 2019 16:08:14GMT0530(印度标准时间),webkitRelativePath:",size:13264,…}长度:2

方法:

 uploadToServer(data) {
for ( let i = 0 ; i < data.length ; i++ ) {

  const fileType = this.fileValidations.getFileExtension(data[i].name);
  const filetype = {file_type : fileType};
  const data1 = {file : data[i]};
  let uploadFormData;
  uploadFormData = (Object as any).assign({}, data1, filetype);

  this.fileUploadService.uploadFile(uploadFormData).subscribe(res => {
    this.documentCount = this.documentCount + 1;

    const currentFileName = data[i].name;
    this.documentDetailsObj.name = res.original_name;
    this.documentDetailsObj.id = res.id;
    this.documentNameArr.push((this.documentDetailsObj));


    console.log(this.documentNameArr);

    // Expected output : 
    // 0: {name: "pdf1.pdf", id: 1}
    // 1: {name: "pdf2.pdf", id: 2}

    // Current Output :
    // 0: {name: "pdf2.pdf", id: 2}
    // 1: {name: "pdf2.pdf", id: 2}





  }, error => {
    console.log('error');
  });
}

}


共1个答案

匿名用户

在这里,您将在下一次迭代中传递对象,相同的对象将通过引用传递更新。

this.documentDetailsObj.name = res.original_name;
this.documentDetailsObj.id = res.id;
this.documentNameArr.push((this.documentDetailsObj));

您只需创建一个对象并将其推送到一行即可,无需额外的变量

this.documentNameArr.push({name: res.original_name, id: res.id});