how to sent array data as formdata angular 4

三世轮回 提交于 2020-01-13 03:39:48

问题


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>

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/48921063/how-to-sent-array-data-as-formdata-angular-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!