linto johny
linto johny

Reputation: 137

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>

Upvotes: 5

Views: 16104

Answers (2)

Eitan Seri-Levi
Eitan Seri-Levi

Reputation: 341

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:...})

Upvotes: 2

Mixalloff
Mixalloff

Reputation: 837

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;
}

Upvotes: 2

Related Questions