[英]Prepare the body of an Http post request from an object
要以角度发送http post请求的正文,请使用以下实现:
let requestBody: String = "";
//dataObjectis the object that contains the values to send from the form
for (let key in dataObject) {
if (dataObject[key]) {
requestBody += (body.length ? '&' : '') + key + "=" + dataObject[key];
}
}
然后在我的http发布请求中使用requestBody
,如下所示:
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let requestOptions = new RequestOptions({ headers: headers });
//http is an Http instance
http.post(URI, requestBody, requestOptions)
我想知道是否有更好的方法或“准备使用”的方法允许直接在post方法中使用对象dataObject
而不是使用上述实现。
我不知道是否有使用过的Http模块的方法。 新的HttpClient支持此功能。
constructor(http: HttpClient) {
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/x-www-form-urlencoded');
let params = new HttpParams()
params = params.set('a', '1')
http.post('/api/v1/login', params, {headers: headers}).subscribe(res => {});
}
尝试使用URLSearchParams
:
import { URLSearchParams } from '@angular/http';
//...
let requestBody = new URLSearchParams();
for (let key in dataObject) {
requestBody.set(key, dataObject[key]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.