来自ng-resource head请求的响应头访问

时间:2015-11-24 16:32:45

标签: javascript angularjs

我通过ngResource提出头部请求,如下所示

let resource = $resource(url, null, {
    head: {
       method: 'HEAD',
       transformResponse: function(data, headers) {
          console.log(headers('X-my-header');
          return data;
       }
    }
}
resource.$head();

它正在提出正确的头部请求,我可以在网络选项卡中看到它;但是,我无法访问HTTP标头。如果我使用$ http,我可以访问这些标头。我想知道,如果有人知道从ngResource HEAD请求访问RESPONSE HEADERS(' X-my-header')的好方法吗?

1 个答案:

答案 0 :(得分:1)

您需要像这样更新transformResponse函数:

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

app.factory('myResource', function ($resource) {
  return $resource('/', {}, {
    head: {
       method: 'HEAD',
       transformResponse: function(data, headers) {
        var response = {};
        response.data = data;
        response.headers = headers();
        response.myCustomValue = headers('X-my-header');
        return response;
       }
    }
  });
})

app.controller('MainCtrl', function($scope, myResource) {
  $scope.name = 'World';
  myResource.head(function successFoo() {

  }, function errorFoo(response) {
    console.log(response.data);
  });
});

Example