Utilizing formData.append in TypeScript to handle arrays

Hey there! I'm facing an issue while trying to send a form to my Profile endpoint. The problem lies in the 'user:{}' field, as I am unable to properly insert my array data into this specific field.

Here is a breakdown of the fields within my endpoint:

{
  "id": 4,
  "ci": "123456",
  "photo": "http://127.0.0.1:8000/media/profiles/12809632_10208569440535095_617453747387788113_n_zAUAVMf.jpg",
  "phone_number": "+59177621589",
  "user": {
    "id": 5,
    "username": "sdanderson",
    "first_name": "ssss",
    "last_name": "ssss"
  },
  "experience": "null",
  "typeskill": [
    {
      "id": 1,
      "skill_name": "developer"
    }
  ]
}

Additionally, here is the service function that I have created for making a PUT request:

putProfile(id:string,token:string,body:any,files:any):Observable<Profile>{

//saving the data to be sent to the endpoint for updating
    let formData: FormData = new FormData();

    for (let file of files) {
        formData.append('photo', file);
    }
    formData.append('ci',body['ci']);  
    formData.append('phone_number', body['phone_number']); 
    formData.append('experience',body['experience']);
    formData.append('user',body['user']);//inside this field, I have: body['user'].id, body['user'].first_name, and body['user'].last_name

    //add headers
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    headers.append("Authorization","Token "+ token);

    return this.http.put(this.api+"profile/"+id+'/',formData,{headers})
        .map(this.extractData)
        .catch(this.handleError);
}

Answer №1

The method append() in FormData can only receive objects of type string or blob. If you want to append an array, you should use the JSON.stringify() method to convert your array into a valid JSON string.

This is how you can do it:

formData.append('user', JSON.stringify(body['user']));

To find out more about JavaScript's JSON object, click here.

Answer №2

you can give this method a shot, it has been successful in my past projects

 let data = new FormData();

    for (let file of files) {
        data.append('image[]', file);
    }

Answer №3

Dealing with a comparable issue, I opted to create an array in the key. In your scenario, it would be implemented as follows:

formData.append('user[id]', body['user']['id']);
...

This method proves beneficial when interpreting JSON on the server side is not feasible or desired.

Answer №4

I needed to include four images under the same formdata id. Here is how I achieved it in my code:

const selectedFiles = event.target.files;
  for(let i=0; i<selectedFiles.length; i++){
    this.formData.append("images", selectedFiles[i]);
  }

Answer №5

My task involved integrating Angular frontend with a Spring backend, where I had to handle a formData containing a file being sent. The additional requirement was to send an array to the backend using the same endpoint for transaction rollbacks.

Note: Another potential and perhaps better approach would have been to utilize spring-boot-multipart-requests

putProfile(id:string,token:string,body:any,files:any):Observable<Profile>{

    let formData: FormData = new FormData();

    for (let file of files) {
        formData.append('photo', file);
    }
   ...
    
    let json = JSON.stringify(body['user']);
    formData.append('jsonUserArray',json);
    
    //service call  
    ...
}

//backend spring boot

@PostMapping("/profile/{id}")
public ResponseEntity<Object> updateProfile(@PathVariable("id") int id,
                                           @RequestParam(required=false) String jsonUserArray,
                                           @RequestParam(required=false) MultipartFile file,
                                           @NotNull(message = "Authentication error.") Authentication authentication) throws Exception {
    ResponseEntity<Object> response = null;
    boolean accept = accept.equals("true") ? true: false;
    //convert the json to list of Users
    ObjectMapper mapper = new ObjectMapper();
    List<User> listUsers = mapper.readValue(jsonUserArray, new TypeReference<List<Users>>(){});
    ...
    //service call  
}

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

Steps to automatically update a component when the button is clicked

Is there a way to change the displayed component in my parent component when clicking on a specific element? I currently have a pie chart component displaying by default but would like to switch it to another component with a different diagram when clickin ...

How can I use a single route in Angular 5 to direct all paths for an outlet to a single component?

Here is my current setup: const routes: Routes = [ { path: '', component: NavComponent, outlet: 'nav' }, // (1) { path: '**', component: NavComponent, outlet: 'nav' } // (2) ]; The configuration is functioning ...

Updating the navigation bar in Node/Angular 2 and displaying the sidebar once the user has logged in

I am facing a challenge with my first project/application built using Angular 2, particularly related to the login functionality. Here is what I expect from the application: Expectations: When I load the login component for the first time, the navbar ...

Connection to mongo is currently unavailable for Middleware next

This code snippet shows a middleware for Next, which is designed to read the subdomain and check if it exists in the database. import { getValidSubdomain } from '@/lib/getValidSubdomain'; import { NextResponse } from 'next/server' impor ...

Updating the display in Angular 4 following modifications to an array

I am puzzled by a certain concept. I came across a notion that the view in my project only updates when some of the variables change their reference. However, I'm confused about how this applies to arrays. When I make changes to an array, sometimes th ...

Creating a loading spinner with the help of an rxjs BehaviorSubject

After creating a loading spinner component for my angular 4 application to display during AJAX calls, I encountered an issue when trying to implement it with a subscription to a BehaviorSubject. This question is similar to how to show a spinner until data ...

Unable to close keyboard on Ionic 5 app for both Android and iOS platforms

Hello there, I'm currently facing an issue trying to hide/dismiss the keyboard on both iOS and Android devices while using the Ionic 5 platform with Angular. I've attempted various methods such as keydown.enter, keyup.enter, and keypress without ...

Having trouble locating module '@angular/http'?

In the configuration file systemjs.config.js for my Angular 2 application, I included the following entry in the map object: '@angular/http': 'https://npmcdn.com/@angular/http' While trying to import '@angular/http' at the b ...

How can I display the value of a radio button that has been chosen?

Would you mind sharing how to display the selected value of a radio button? I attempted it this way, but unfortunately, it did not work. You can view my code at this link. <mat-radio-group [(ngModel)]="favoriteName"> <mat-radio-button *ngFor="l ...

Solving Checkbox Change Event Issue in Angular

I'm having difficulty testing the checkbox-change event for a particular component. Here is the code for the component that needs to be tested: import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: &a ...

Define the static property as an array containing instances of the same type

I created a class called Foo with a static property named instances that holds references to all instances. Then, I have another class called Bar which extends Foo: class Foo { static instances: Foo[]; fooProp = "foo"; constructor() { ...

Tips for Integrating an Angular App into a Different Website

I have an Angular application hosted at www.A.com, My client has a website hosted at www.B.com I am looking to enable my client to embed the Angular app on their webpage without physically copying the application files. I want them to simply add some HTML ...

The Angular framework always initializes the list items in CDK drop List starting from the initial index

Currently, I am working with the cdk Drag drop feature <div class="example-container" cdkDropListGroup> To properly understand and describe data, it is crucial to be aware of the level of variability. This can be determined by analyzing the ...

Sorting List Algorithm

Looking to create an algorithm in Node.js that abides by specific rules. It takes a series of numbers as input and the maximum consecutive number before taking a break. The logic is as follows: The rules : Only one competition per day Competitions are hel ...

Access the array values by their respective keys in an object that is returned from a custom JavaScript file utilizing the Node.js file system

I recently came across a config file with a unique format, as shown below: define([], function () { return { productItems: { item1: ['Apple', 'Ball', 'Car'], item2: [&apo ...

ag-Grid open-source server-side filtering

Currently, I am utilizing the ag-grid community version for my project. I am inquiring whether it includes support for server side filtering and paging. If not, what alternative methods can be used to implement filtering with the ag-grid community versio ...

Angular and Ionic collaborate by using ngFor to pass on the item.id during a (click) event

I have a list of items and I want to dynamically change the height of a card when I click on a button that is located on the card. Can anyone guide me on how to achieve this? I attempted to pass the item.id through a click event and use the id in a functi ...

Ways to initiate an HTTP request within switchMap upon emission of a BehaviorSubject value

As I delve into writing angular applications in a declarative style, I find myself pondering on the most effective approach for handling POST requests. Specifically, I am facing a dilemma with regards to calling these requests when dealing with a login for ...

Exporting several functions within a TypeScript package is advantageous for allowing greater flexibility

Currently, I am in the process of developing an npm package using Typescript that includes a variety of functions. Right now, all the functions are being imported into a file called index.ts and then re-exported immediately: import { functionA, functionB ...

The system is unable to process the property 'items' due to a null value

When trying to access the properties of ShoppingCart, an error is encountered stating that Property item does not exist on type {}. The mistake made in the code is unclear and difficult to identify. shopping-cart.ts import { ShoppingCartItem } from &apos ...