簡體   English   中英

在 AJAX 調用成功響應時將數據推送到數組中會導致多次附加最后一個數據

[英]Pushing the data in an array on success response of an AJAX call leads to appending the last data multiple times

我正在嘗試僅 append 文件上傳成功響應的數組中的數據。 在循環控制台內給出正確的 output 但結果數組由復制數據組成(最后一個數據重復 n 次)

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

例子:

FileList {0: File, 1: File, length: 2} 0: File {name: "demoform1.pdf", lastModified: 1565685422300, lastModifiedDate: Tue Aug 13 2019 14:07:02 GMT+0530 (India Standard Time), webkitRelativePath: "", size: 20061, ...} 1: File {name: "dummy.pdf", lastModified: 1565260694049, lastModifiedDate: Thu Aug 08 2019 16:08:14 GMT+0530 (India Standard Time), webkitRelativePath: " ",大小: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');
  });
}

}

在這里,您將在下一次迭代中傳遞 object,相同的 object 通過引用傳遞更新。

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

您可以只創建一個 object 並將其推入一行,無需額外的變量

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM