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

Retrieve data from child routes within the parent component

In my Angular module routing structure, I have a parent component that contains child components represented as tab items. Here is the routing setup: { path: "teacher/:id", component: TeacherTabcontrolComponent, children: [ { path: & ...

Get rid of the strange border on the material dialog

I am struggling with the Angular material 6 dialog component as it is displaying a strange border. I have attempted to remove it using the code below, without success. Interestingly, when I apply the style inline in the browser, it works fine. Any suggesti ...

What are some ways to incorporate advanced/nested type variables when using arrow functions?

Is there a way to use "advanced/nested" type variables, similar to how T is utilized in this function declaration, when working with arrow functions? function wrapInObject<T>(key: string) { return (x: T) => ({ [key]: x }); } I attempted to ach ...

Issue with importing aliases in Angular 7 production environment

Hello everyone! I have encountered an issue where using alias on import and building the project in production mode (--prod flag) results in the alias being undefined. Interestingly, this behavior does not occur in development mode. Any suggestions on how ...

Global Inertia Headers

How can I ensure that a custom header (Accept-Content-Language) is sent with every request, including Inertia manual visits? Below is the code snippet where I define and set the header: import axios from 'axios'; const lang = localStorage.getIt ...

Is the validity of the expression !args.value || args.value.length true?

After analyzing this segment of code, I noticed an interesting expression: !args.value || args.value.length For instance, consider the following scenario: let v = {}; console.log(!v.value); //outputs true console.log(v.value); //outputs undefined con ...

Establish an enumeration using universally recognized identifiers

I have a JavaScript function that requires a numerical input, as well as some predefined constants at the top level: var FOO = 1; var BAR = 2; The function should only be called using one of these constants. To ensure type safety in TypeScript, I am att ...

Unable to resolve the Typescript module within a different file

I am in the process of transitioning my React app to TypeScript. Currently, everything is working fine. However, I encountered an issue after adding the TypeScript compiler and renaming files to .ts and .tsx extensions - it is now throwing a "module not fo ...

Experiencing difficulty in transferring array information from a parent component to a child component within an

I'm currently working on a task where I need to pass data from a parent component to a child component. The data consists of an array that is nested within another array. parent.component.html <div *ngFor="let parent of parentArray; index as ...

Is there a way to verify in Angular whether an image link has a width and height exceeding 1000?

I'm currently working on a function that checks if an image linked in an input field has a width and height greater than 1000 pixels, and is in JPG format. Here's my approach: HTML: <input (change)="checkValidImage(1, product.main_photo)" [ ...

Using Angular Typescript with UWP causes limitations in accessing C# WinRT component classes

Currently, I am working on a UWP application built with Angular5 and I would like to incorporate Windows Runtime Component(Universal) classes into the application to access data from a table. import { Component,OnInit } from '@angular/core'; @C ...

Modifying SASS variable within an Angular 2 TypeScript project

How can I update the Sass color variable based on user input in Angular 2? I came across a helpful resource, but it doesn't include any examples specifically for Angular 2. Any assistance would be greatly appreciated. Thank you! ...

An issue has been identified with the functionality of the router-out

Issue with Router Loading Component Outside of the router-outlet in app.component.ts @Component({ selector : "body", template : `<router-outlet></router-outlet>`, directives: [ROUTER_DIRECTIVES] }) @RouteConfig([ {path: "/aut ...

My inquiry was met with silence from the Angular project

I have encountered an issue with my dockerized angular project. Upon starting my container, it appears that the 4200 port is already in use, even though the CMD command within the container does not initiate the application startup. Here is how my Docke ...

Retrieve the value of a property within the same interface

Is there a way to access an interface prop value within the same interface declaration in order to dynamically set types? I am attempting something like this: export type MethodNames = "IsFallmanagerUpdateAllowed" | "UpdateStammFallmanager& ...

fesm2020/ngx-translate-multi-http-loader.mjs:2:0-41 - Whoops! Looks like the module couldn't be located

After updating my ngx-translate-multi-http-loader from version 8.0.2 to 9.3.1, I encountered a module not found error. The error message is as follows: ./node_modules/ngx-translate-multi-http-loader/fesm2020/ngx-translate-multi-http-loader.mjs:2:0-41 - Err ...

Modifying the name of a key in ng-multiselect-dropdown

this is the example data I am working with id: 5 isAchievementEnabled: false isTargetFormEnabled: true name: "NFSM - Pulse" odiyaName: "Pulse or" when using ng-multiselect-dropdown, it currently displays the "name" key. However, I want ...

Error occurs when using JSON.stringify with a Typescript array map

When running this code snippet in Typescript: [].map(JSON.stringify); An error is being thrown: Argument of type '{ (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: any, ...

Is it possible to integrate ngx-translate with database-supported translations?

I am managing a vast database (pouchDB) that stores translations, with each language having its own dedicated database. How can I leverage ngx-translate to easily access these translations directly from the database? ...

Need to import a JSON file and convert it to an interface in order to ensure that all fields are included

I am facing an issue where I am attempting to parse a json file using require(). My goal is to convert it into a specific data type and have the conversion fail if the file does not contain all the necessary fields as defined by the interface. Below is my ...