Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sent array data as formdata angular 4

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>
like image 906
linto johny Avatar asked Feb 22 '18 06:02

linto johny


2 Answers

Right now your deleteCategory() method is making a POST request to the specified endpoint with an empty request body.

Here is a simple example on how to include an array of objects in a POST request using Angulars HttpClient

this.http.post('some url', JSON.stringify(yourArrayOfObjects), {headers: ...})

If you wanted to send FormData (if for example you're uploading a file to a server)

 const frmData = new FormData();
 frmData.append("fileUpload", file)
 this.http.post('some url', frmData, {headers:...})
like image 89
Eitan Seri-Levi Avatar answered Nov 05 '22 05:11

Eitan Seri-Levi


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;
}
like image 25
Mixalloff Avatar answered Nov 05 '22 03:11

Mixalloff