JulieMarie
JulieMarie

Reputation: 402

Can't get only the header in AngularJS (v1.3.15) using $resource and method 'HEAD'

In Angular (v1.2.19), I was able to do something like this in a factory :

myApp.factory('GetNumber', ['$resource',
  function($resource) {
    var get_headers = $resource('some/url', null, {
      get_number: {
        method: 'HEAD',
        transformResponse: function(data, headers) {                            
          var count = headers()['x-number'];
          return count;
        }
      }
    });
    return get_headers;
  }
]);

Call it from my controller like this:

$q.all({
  'item1': GetNumber.get_number().$promise,
  'item2': SomeOtherService.get().$promise
})
.then(function(results) {
  $scope.newNumber = results.item1.value;
});

And I could get the custom header back without having to retrieve the whole header.

Now in v1.3.15, it doesn't work. I can see the header in Chrome with 'x-number' in the header, but if I put a breakpoint in Chrome on the 'var count' line, I never hit it (and I do hit it with v1.2.19).

I've verified that using $http.head works, so if I have this in my controller:

$http.head('some/url')
    .success(function(data, status, headers, config) {
         var count =  headers()['x-number'];
         $scope.newNumber = count ? count : 0;
    });

I get my scoped value.

I've noticed that there aren't a whole lot of examples of people using the http 'HEAD' method and I'm wondering if there's a reason that I haven't located yet through searching?

I did find this StackOverflow question and answer HTTP Get: Only download the header? (HEAD is not supported) and while I agree with the statement, I don't want the overhead of requesting the headers and the body.

Any suggestions please? Julie

Upvotes: 0

Views: 234

Answers (1)

JulieMarie
JulieMarie

Reputation: 402

Thank you to Kevin for suggesting that I use an error handler. I should've thought to try that myself, but I didn't.

Anyway, that lead me to the answer to my problem. To try and catch an error in $resource, it's suggested you use interceptors. I've never used them before and I utilized AngularJS documentation (https://docs.angularjs.org/api/ng/service/$http#interceptors) and changed the code in my factory to be:

myApp.factory('GetNumber', ['$resource',
  function($resource) {
    var get_headers = $resource('some/url', null, {
      get_number: {
        method: 'HEAD',
        interceptor: { response: function(response) {
          var count = response.headers()['x-number']:
          return count ? count : 0;
        }, responseError: function(rejection) {
          console.log('rejection: ', rejection);
        }}
      }
    });
    return get_headers;
  }
]);

I'm still not sure why transformResponse stopped working and I now need to use interceptor, but very happy I don't have to request the whole body now!

Julie

Upvotes: 1

Related Questions