【发布时间】:2019-05-21 04:12:09
【问题描述】:
AngularJS 代码到 Angular 2+ 代码 - Http 问题
我正在将一些较旧的 AngularJS 代码(实际上是其 Ionic 1)转换为较新的 Angular(Ionic 4),但遇到了一个烦人的问题。
所以在 AngularJS 中的每一个 Http Post 上,之前的开发者都是这样做的:
var headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
// Add authentication headers if required
if (token) headers['x-auth-token'] = token;
if (userid) headers['x-auth-id'] = userid;
var config = {
url: api(endpoint),
method: method,
headers: headers
};
if (method == 'GET') {
config['params'] = data;
} else {
config['data'] = $httpParamSerializerJQLike(data);
}
return $http(config).then(function(response) {
return response.data;
});
手头的问题是这一行:$httpParamSerializerJQLike(data);
在 Angular 2+ 中,这不存在并且会导致问题。
有人可以帮我把它转换成新版本的 Angular 吗?
这是我目前所拥有的:
let headers = {
"Content-Type": "application/x-www-form-urlencoded"
};
if (this.token) headers["x-auth-token"] = this.token;
if (this.userid) headers["x-auth-id"] = this.userid.toString();
let config = {
url: await this.api(endpoint),
method: method,
headers: headers,
body: data
};
if (method === "GET") {
config["params"] = data;
return await this.http.get(config["url"], config).toPromise();
} else {
config["data"] = await this.formatData(data);
return await this.http
.post(config["url"], config["data"], config)
.toPromise();
}
如您所见,我创建了这个 formatData() 函数,它试图序列化数据,但它不能 100% 工作。特别是当有嵌套的 JSON 数据时。
这是我创建的 formatData 函数:
async formatData(obj) {
var str = [];
for (var key in obj) {
if (obj != undefined) {
if (obj.hasOwnProperty(key)) {
str.push(
encodeURIComponent(key) + "=" + encodeURIComponent(obj[key])
);
}
}
}
return str.join("&");
}
非常感谢任何帮助!如果有人知道我可以安装的任何库或与此库类似的任何东西:$httpParamSerializerJQLike(data);
【问题讨论】:
-
以
application/json发送数据。不要打扰application/x-www-form-urlencoded。 -
如果必须使用
application/x-www-form-urlencoded,请使用jQuery param对数据进行编码。 -
是的,由于后端限制,我必须使用
x-www-form-urlencoded。所以我正在尝试使用@angular/common/http让它工作你能给我一个使用jQuery.param 转换一些嵌套JSON 的例子吗? -
@georgeawg 请让 jQuery.param 评论成为答案。我会选择一个最佳答案。
标签: angular typescript ionic-framework