如何访问 ngResource 响应的原始 JSON 字符串?

How to access raw JSON string of ngResource response?

我使用 ngResource 查询 JSON 服务,默认情况下 Angular 解析响应。不幸的是,我还想访问原始响应字符串。

这是我想要实现的目标的片段:

var app = angular.module('plunker', ['ngResource']);

app.factory('DateResource', function($resource, $http) {
  var raw = null,
    resource = $resource('http://date.jsontest.com/', {}, {
      query: {
        method: 'GET',
        transformResponse: [
          function(data) {
            raw = data;
            return data;
          }
        ].concat($http.defaults.transformResponse).concat([
          function(data) {
            data.$raw = raw;
            return data;
          }
        ])
      }
    });
  return resource;
});

app.controller('MainCtrl', function($scope, DateResource) {
  DateResource.query({}, function(response) {
    console.log('response:', response); // should be parsed JSON object
    console.log('response.$raw:', response.$raw); // should be raw JSON string
  });
});

查看完整示例:http://plnkr.co/edit/RSwrRQFo1dEGDkxzRTcF

这种在父作用域中使用两个 transformRequest 函数和一个 raw 变量的实现并不是一个好主意,因为调用可能是异步的...

是否有可能识别响应,以便我可以记住每个响应的原始内容并稍后在第二个 transformResponse 中附加?或者您知道其他解决方案吗?

 var app = angular.module('plunker', ['ngResource']);

app.factory('DateResource', function($resource, $http) {
  var raw = null,
    resource = $resource('http://date.jsontest.com/', {}, {
      query: {
        method: 'GET',

      }
    });
  return resource;
});

app.controller('MainCtrl', function($scope, DateResource) {
  DateResource.query({}, function(response) {
    console.log('response:', response); // should be parsed JSON object
    console.log('response.$raw:', angular.toJson(response)); // should be raw JSON string
  });
});

请参阅下文 link 以获得清晰的理解:

https://docs.angularjs.org/api/ngResource/service/$resource

您可以通过覆盖转换默认值并使用 angular.fromJson(rawData)

resource = $resource('http://date.jsontest.com/', {}, {
  query: {
    method: 'GET',
    transformResponse: transformGet
  }
});


function transformGet(json, headerGetter) {
  var fromJson = angular.fromJson(json);
  fromJson.json = json ;
  return fromJson;
}

笨蛋:http://plnkr.co/edit/uIIdKAeUwRN4ThUlMsvd

希望有所帮助