如何将数组数据作为表单数据发送 angular 4
how to sent array data as formdata angular 4
我试过 post 一组数据没有发送到服务器:
网络服务:
deleteCategory() {
return this.http.post('http://www.demo/webapi/deletecategory', {
headers: {
"Authorization": "Token " + this.token,
"Content-Type": "application/x-www-form-urlencoded"
},
withCredentials: true
}
)
}
在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);
}
})
}
在 html
<button class="btn-danger pull-right" (click)="onDelete()" type="button" >Delete</button>
您必须创建 FormData
对象并将您的数组附加到该对象中。看起来像
function createFormData(yourArray) {
const fd = new FormData();
fd.append(
'keyName',
new Blob( [ JSON.stringify( yourArray ) ], { type : 'application/json' } ) );
return fd;
}
现在您的 deleteCategory()
方法正在向指定端点发出 POST 请求,请求主体为空。
这是一个简单的示例,说明如何使用 Angulars HttpClient
在 POST 请求中包含对象数组
this.http.post('some url', JSON.stringify(yourArrayOfObjects), {headers: ...})
如果您想发送 FormData(例如,如果您要将文件上传到服务器)
const frmData = new FormData();
frmData.append("fileUpload", file)
this.http.post('some url', frmData, {headers:...})
我试过 post 一组数据没有发送到服务器:
网络服务:
deleteCategory() {
return this.http.post('http://www.demo/webapi/deletecategory', {
headers: {
"Authorization": "Token " + this.token,
"Content-Type": "application/x-www-form-urlencoded"
},
withCredentials: true
}
)
}
在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);
}
})
}
在 html
<button class="btn-danger pull-right" (click)="onDelete()" type="button" >Delete</button>
您必须创建 FormData
对象并将您的数组附加到该对象中。看起来像
function createFormData(yourArray) {
const fd = new FormData();
fd.append(
'keyName',
new Blob( [ JSON.stringify( yourArray ) ], { type : 'application/json' } ) );
return fd;
}
现在您的 deleteCategory()
方法正在向指定端点发出 POST 请求,请求主体为空。
这是一个简单的示例,说明如何使用 Angulars HttpClient
在 POST 请求中包含对象数组this.http.post('some url', JSON.stringify(yourArrayOfObjects), {headers: ...})
如果您想发送 FormData(例如,如果您要将文件上传到服务器)
const frmData = new FormData();
frmData.append("fileUpload", file)
this.http.post('some url', frmData, {headers:...})