how to sent array data as formdata angular 4

linto johny picture linto johny · Feb 22, 2018 · Viewed 13.5k times · Source

I tried to post an array of data is not sending to server:

webservice:

 deleteCategory() {
    return  this.http.post('http://www.demo/webapi/deletecategory', { 
        headers: {
          "Authorization": "Token " + this.token,
          "Content-Type": "application/x-www-form-urlencoded"
        },
        withCredentials: true
      }
      )
    }

in ts file

onDelete() {
      this.userService.deleteCategory().subscribe(response => {
      this.selectedArray = [];
     for (var i = 0; i< this.selection._selected.length; i++){
     this.selectedArray.push(this.selection._selected[i].category_id) ;
     console.log(' selected value:', this.selectedArray);

     }
    })
      }

in html

<button class="btn-danger pull-right" (click)="onDelete()" type="button"  >Delete</button>

Answer

Mixalloff picture Mixalloff · Feb 22, 2018

You have to create FormData object and append you array in this object. It's looks like

function createFormData(yourArray) {
  const fd = new FormData();
  fd.append(
    'keyName',
     new Blob( [ JSON.stringify( yourArray ) ], { type : 'application/json' } ) );
  return fd;
}