Get response header in then() function of a ngResource object's $promise property after resource resolved?

Uice Stone picture Uice Stone · Apr 6, 2014 · Viewed 13.7k times · Source

I'm willing to retrieve the response header of a resource request, cause I've put pagination information and something else in it rather than the response body, to make the REST api clear.

Though we can get it from the success / error callback like below:

Object.get({type:'foo'}, function(value, responseHeaders){
    var headers = responseHeaders();
});

Where 'Object' is my resource factory service.

Further, when I'm trying to make the route change after required resources resolved, I've tried this:

.when('/list', {
    templateUrl: 'partials/list.html',
    controller: 'ListCtrl',

    // wait for the required promises to be resolved before controller is instantialized
    resolve: {
        objects: ['Object', '$route', function(Object, $route){
            return Object.query($route.current.params).$promise;
        }]
    }
})

and in controller, just inject "objects" instead of Object service, because it's resolved and filled in with real data.

But I got problem when I try to get headers info from the "objects" in controller.

I tried objects.$promise.then(function(data, responseHeaders){}), but responseHeader was undefined.

How can I change the $resource service's behavior so that it throws the responseHeader getter into the $promise then() callback function?

My service "Object" for reference:

myServices.factory('Object', ['$resource',
    function($resource){
        return $resource('object/:id', {id: '@id'}, {
            update: {method: 'PUT'},
        });
    }
]);

Answer

Benoît Bouré picture Benoît Bouré · Jan 2, 2016

I had the exact same problem. I used an interceptor in the resource definition to inject the http headers in the resource.

$resource('/api/resource/:id', {
    id: '@id'
  }, {
    index: {
      method: 'GET',
      isArray: true,
      interceptor: {
        response: function(response) {
          response.resource.$httpHeaders = response.headers;
          return response.resource;
        }
      }
    }});

Then, in the then callback, the http headers are accesible through $httpHeaders:

promise.then(function(resource) {
    resource.$httpHeaders('header-name');
});