我对AngularJS的$http有一种奇怪的行为,并不是真的理解transformResponse是如何工作的(文档对此有点轻描淡写)。
WebAssets.get = function () {
return $http.get('/api/webassets/list', {
transformResponse: [function (data, headersGetter) {
// not sure what to do here?!
return data;
}].concat($http.defaults.transformResponse) // presume this isn't needed, added for clarity
}).then(function (response) {
return new WebAssets(response.data);
});
};api返回一个对象数组:
[{"webasset_name": "...", "application_id": "...", "etc": "..."}, ... ]但是,当transformResponse完成了它的邪恶业务时,数据已经转换为索引对象:
{"0":{"webasset_name":"...","application_id":"...", "etc": "..."}, "1":....}我想保留原始的数据结构(一个对象数组)。
发布于 2013-09-03 07:57:51
要使angular不将数据转换为对象,您需要覆盖默认$httpProvider.defaults.transformResponse的行为。它实际上是一组转换器。您可以将其设置为空:$http.defaults.transformResponse = [];这里是我用来将64位长整数转换为字符串的示例转换器:
function longsToStrings(response) {
//console.log("transforming response");
var numbers = /("[^"]*":\s*)(\d{15,})([,}])/g;
var newResponse = response.replace(numbers, "$1\"$2\"$3");
return newResponse;
}要将转换器添加到默认列表中,例如在JSON反序列化程序之前,您可以这样做:
$http.defaults.transformResponse.unshift(longsToStrings);发布于 2015-05-27 03:34:23
资源0:"f“1:"a”2:"l“3:"s”4:"e“这终于对我起作用了:
transformResponse: function (data, headersGetter) {
return { isCorrect: angular.fromJson(data) }
}发布于 2015-07-03 22:30:08
https://stackoverflow.com/questions/18147126
复制相似问题