Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

javascript - AngularJS, $http and 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);
        });
    };

The api returns an array of objects:

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

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...