【问题标题】:AngularJS, $http and transformResponseAngularJS、$http 和 transformResponse
【发布时间】:2013-08-11 09:52:30
【问题描述】:

我在使用 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":....}

我想保留原始数据结构(对象数组)。

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

要让 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);

【讨论】:

    【解决方案2】:

    资源 0:“f” 1:“a” 2:“l” 3:“s” 4:“e” 这终于对我有用了:

       transformResponse: function (data, headersGetter) {
        return { isCorrect: angular.fromJson(data) }
        }
    

    【讨论】:

      【解决方案3】:

      尝试使用资源查询方法

      https://github.com/angular/angular.js/issues/6314

      【讨论】:

      • 我认为您需要做的是通知 $http 您正在返回数组而不是对象
      • 你能用一些示例代码扩展你的答案吗?查看代码和描述总是更清楚。你可以edit你的答案。顺便问一下,你为什么要创建两个帐户?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      • 1970-01-01
      • 1970-01-01
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      相关资源
      最近更新 更多