Executing multiple http post requests in Angular2 using a for loop

I've encountered an issue while attempting to upload multiple files with individual titles. The problem arises when sending requests to the server, as I'm trying to pass each file and its corresponding title one by one. I have an array called bindArray which stores data in the following format:

bindArray = [{file: File(), title: 'abc'}, {file:File(), title: 'bcd'}]

Currently, I am using a loop through the array to send each file and title to the server. However, after successfully sending the request for index [0] of bindArray, the subsequent request for index [1] also includes the data from index [0], leading to a failure. Upon inspecting the network tab in Chrome console, I observed that while requesting index [1], the previous file and data are unintentionally being sent along, causing errors. Despite researching potential solutions for this issue, none seem to work as desired. I'm perplexed as to why this behavior is occurring.

Below is the complete code snippet:

upload.html

<input id="cin" name="file" type="file" (change)="fileChangeEvent($event)"
   multiple placeholder="Upload a file..."/>

<form #submitCertificate="ngForm">
  <div class="input" *ngFor="let a of titleArray">
    <input type="text" [(ngModel)]="a.title" name="title" *ngIf="showInput" (blur)="blurMethod()" placeholder="title"> <br>
  </div>
</form>
<button type="submit" (click)="upload('certificate')">upload</button>

upload.component.ts

 files;
 formData;
 titleArray = [];
 showTitle: boolean = false;
 showInput: boolean = false;

 blurMethod() {
  this.title = this.titleArray;
 }

 fileChangeEvent(evt) {
   this.showInput = true;
   this.files = evt.target.files;
   for (let i = 0; i < this.files.length; i++) {
    this.addTitle();
   }
 }

 upload(docType) {

   if (this.files.length > 0) {
    let file;
    let title;
    const bindArray = [];
    this.formData = new FormData();
    for (let i = 0; i < this.files.length; i++) {
      for (let j = 0; j <= i; j++) {
        file = this.files[i];
        title = this.titleArray[j].title;

        if (i === j) {
          this.imageNameArray.push(file.name);
          bindArray.push({
            file: file,
            title: title
          });
       }
     }
   }
   for (let k = 0; k < bindArray.length; k++) {
     let formFile = {name: ''};
     let formFileName = '';
     let formTitle = '';
     formFile = bindArray[k].file;
     formFileName = formFile.name;
     formTitle = bindArray[k].title;
     this.formData.append('file', formFile, formFileName);
     this.formData.append('title', formTitle);

     this.doctorService.uploadDocuments(this.formData, docType)
       .subscribe(response => {
         console.log(response, "response")
       }, err => {
        console.log(err, 'err');
       });
   } 
}

doctorService.ts

 uploadDocuments(formData, docType) {
   const headers = new Headers();
   headers.append('type', docType);

   return this.apiHelperService.post('https://someurl', formData, {headers: headers})
    .map(response => {
      return response.json();
    })
    .catch(this.handleError);
 }

Answer №1

To ensure that the formData only contains one record, it is necessary to create a new instance of FormData for each loop iteration.

for (let k = 0; k < bindArray.length; k++) {
 let formFile = {name: ''};
 let formFileName = '';
 let formTitle = '';
 formFile = bindArray[k].file;
 formFileName = formFile.name;
 formTitle = bindArray[k].title;
 this.formData.append('file', formFile, formFileName);
 this.formData.append('title', formTitle);

 // add these lines
 const uploadData = this.formData;
 this.formData = new FormData();
 // add these lines

 this.doctorService.uploadDocuments(uploadData, docType)
   .subscribe(response => {
     console.log(response, "response")
   }, err => {
    console.log(err, 'err');
   });
} 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to setting up identically named properties in Child container components

As I am still fairly new to React and its concepts, I may not be executing this correctly. Although the question might seem lengthy, I'll try my best to keep it simple. I have created a component for TableHead that extends some material-ui components ...

Tips on utilizing a connected service in a custom Azure DevOps extension's index.ts file

I have created a unique extension for Azure DevOps that includes a specialized Connected Service and Build task. When setting up the task through the pipeline visual designer, I am able to utilize the Connected Service to choose a service and then populate ...

The specified module could not be located in the ngx-toastr library

I'm having trouble finding the solution... ERROR in ./node_modules/ngx-toastr/fesm5/ngx-toastr.js Module not detected: Error: Unable to locate '/Users/vasanthan/Mean projects/node_modules/@angular/animations' in '/Users/vasanthan/Mean ...

What could be causing my node server to display a blank page when it is pointing to the /dist folder of an Angular application?

Currently, my node server setup is as follows: const express = require('express'); const app = express(); app.get('*', (req, res) => { res.sendFile(__dirname + '/dist/page/index.html'); }) app.listen(3335, () => { c ...

Database records failing to update after deployment

After deploying my next js site using Vercel, I encountered an issue with the functionality related to adding, getting, editing, and deleting data from MongoDB. Although all functions were working perfectly locally, once deployed, I noticed that while I co ...

Guide to incorporating Moengage into Node.js APIs for delivering email notifications based on user interactions

How can Moengage be integrated into Node Js APIs for sending notifications to users based on user events? I have reviewed the Moengage API documentation but did not find relevant information on integrating Moengage with Node Js APIs. Is there a step-by-s ...

Controlling Ionic 3 slides on a separate page

I have a collection of slides on one page, each slide representing a different page. I am looking to create a functionality where clicking a button on one of the pages will advance the slide to the next one: slides-page.ts @ViewChild(Slides) slides: Slid ...

Utilizing Angular 2 to Fetch Data from API during Initialization

I'm currently facing an issue in my Angular service where I am attempting to call an API to retrieve user data based on the ID stored in localStorage. However, the API doesn't seem to be getting called at all. Can anyone provide assistance with t ...

A versatile Material UI paper that adjusts its dimensions dynamically

Utilizing Material-UI's Paper component (https://mui.com/components/paper/), I've encountered a scenario where the content within the Paper element needs to be dynamic. <Paper className="modal" elevation={3}> ...Content </Paper ...

Maintain synchrony of the state with swiftly unfolding occurrences

I developed a custom hook to keep track of a state variable that increments based on the number of socket events received. However, when I tested by sending 10 simultaneous events, the total value of the state variable ended up being 6, 7, or 8 instead of ...

Typescript is throwing an error when trying to use MUI-base componentType props within a custom component that is nested within another component

I need help customizing the InputUnstyled component from MUI-base. Everything works fine during runtime, but I am encountering a Typescript error when trying to access the maxLength attribute within componentProps for my custom input created with InputUnst ...

How can I convert duplicate code into a function in JavaScript?

I have successfully bound values to a view in my code, but I am concerned about the duplicate nested forEach loops that are currently present. I anticipate that Sonarcube will flag this as redundant code. Can anyone advise me on how to refactor this to avo ...

Error: Idle provider not found in the promise

Currently, I am integrating ng2-idle into an AngularJS 2 application. After successfully including the ng2-idle package in the node_modules directory of my project, I attempted to import it into one of my components as shown below: Dashboard.component.ts: ...

Retrieve information using Angular's EventEmitter

Recently I started learning Angular and encountered a challenging issue that has kept me occupied for the past few hours. I have implemented a parent-child relationship between two components, with a need to share a boolean variable from the parent to the ...

Manage the appearance of a component using props

Here is the code snippet that I am working with: export type BreadcrumbItemProps = { isCurrent?: boolean; }; const isCurrent = (props: { isCurrent?: boolean }) => props.isCurrent ? 'normal' : 'bold'; export const Item = styled.s ...

Issues with Angular 5 and Firebase integration

After updating my computer to High Sierra with a clean install, reinstalling the angular-cli, and cloning one of my previous projects that uses Firebase and angularfirebase2, I encountered an issue where any operation to get data from Firebase is not worki ...

Error: Unable to access $rootScope in the http interceptor response function

I have set up an interceptor to display an ajax spinner while loading. interface IInterceptorScope extends angular.IRootScopeService { loading: number; } export class Interceptor { public static Factory($q: angular.IQService, $ro ...

What is the Angular2 version of angular.equals?

Currently, I am in process of upgrading an Angular 1 project to Angular 2. In the old project, I used angular.equals for comparing objects like this: angular.equals($ctrl.obj1, $ctrl.newObj);. I tried looking online for a similar method in Angular 2 but ...

The error was thrown by the internal module loader in Node.js at line 1029

I encountered this Console Error - "Error: Cannot find module". Below is the detailed error message in the console. Any solutions? node:internal/modules/cjs/loader:1029 throw err; ^ Error: Cannot find module '/home/hiranwj/list' at Mo ...

What is the best way to assign JSON data to a Class variable within Angular?

In my code, I have a class called Projects export class Projects { project_id: number; project_name: string; category_id: number; project_type: string; start_date: Date; completion_date: Date; working_status: string; project_info: string; area: string; add ...