如何将数组数据作为 formdata angular 4 发送

lin*_*hny 5 http-post angular-http angular

我试图发布一组未发送到服务器的数据:

网络服务:

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

在 ts 文件中

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

     }
    })
      }
Run Code Online (Sandbox Code Playgroud)

在 html 中

<button class="btn-danger pull-right" (click)="onDelete()" type="button"  >Delete</button>
Run Code Online (Sandbox Code Playgroud)

小智 2

现在,您的deleteCategory()方法正在使用空请求正文向指定端点发出 POST 请求。

下面是一个关于如何使用 Angulars HttpClient 在 POST 请求中包含对象数组的简单示例

this.http.post('some url', JSON.stringify(yourArrayOfObjects), {headers: ...})
Run Code Online (Sandbox Code Playgroud)

如果您想发送 FormData(例如您要将文件上传到服务器)

 const frmData = new FormData();
 frmData.append("fileUpload", file)
 this.http.post('some url', frmData, {headers:...})
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用的是 httpClient (不是“旧时尚”http),则不需要 JSON.stringify (2认同)