AngularJS,$ http和transformResponse [英] AngularJS, $http and transformResponse

查看:151
本文介绍了AngularJS,$ http和transformResponse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到与AngularJS的一个奇怪的行为$ HTTP并没有真正理解transformResponse如何工作(该文档是在这一个有点轻)。

I'm getting a strange behaviour with AngularJS's $http and not really understanding how transformResponse works (the docs are a bit light on this one).

    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返回对象的数组:

The api returns an array of objects:

[{"webasset_name": "...", "application_id": "...", "etc": "..."}, ... ]

但是,当transformResponse做它的邪恶的业务数据转化成一个索引对象:

But when transformResponse has done it's evil business the data has transformed into an indexed object:

{"0":{"webasset_name":"...","application_id":"...", "etc": "..."}, "1":....}

我要保留原始数据结构(一个对象数组)。

I want to keep the original data structure (an array of objects).

推荐答案

要获得角度来不是你的数据转换成你需要覆盖默认$ httpProvider.defaults.transformResponse的行为的对象。它实际上是变压器的阵列。
你可以只将其设置为空: $ http.defaults.transformResponse = [];
下面是一个例子变压器我已经习惯了64位长整数转换为字符串:

To get angular to not convert your data into an object you need to override the behavior of the default $httpProvider.defaults.transformResponse. It is actually an array of transformers. You could just set it to be empty: $http.defaults.transformResponse = []; Here is an example transformer I have used to convert 64-bit long ints to strings:

function longsToStrings(response) {
    //console.log("transforming response");
    var numbers = /("[^"]*":\s*)(\d{15,})([,}])/g;
    var newResponse = response.replace(numbers, "$1\"$2\"$3");
    return newResponse;
}

要变压器添加到默认列表中,说领先于JSON解串器,你可以这样做:

To add a transformer to the default list, say ahead of the JSON deserializer, you can do this:

$http.defaults.transformResponse.unshift(longsToStrings);

这篇关于AngularJS,$ http和transformResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆