Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access response headers using $resource in Angular?

I basically call get requests like so:

var resource = $resource('/api/v1/categories/:id')

resource.get({id: 1}).$promise.then(function(data){
  console.log(data)
})

This works fine.. but how do I get the response headers?

like image 689
Nathan Avatar asked Feb 09 '15 08:02

Nathan


3 Answers

You could use the transformResponse action defined here this would allow you add the headers

$resource('/', {}, {
    get: {
        method: 'GET',
        transformResponse: function(data, headers){
            response = {}
            response.data = data;
            response.headers = headers();
            return response;
        }
    }

See a working example here JSFiddle

like image 68
Martin Avatar answered Oct 29 '22 04:10

Martin


@Martin's answer works for same domain requests. So I would like to add to his answer that if you are using cross domain requests, you will have to add another header with Access-Control-Expose-Headers: X-Blah, X-Bla along with the Access-Control-Allow-Origin:* header.

where X-Blah and X-Bla are custom headers.

Also you do not need to use transform request to get the headers. You may use this code:

var resource = $resource('/api/v1/categories/:id')

resource.get({id: 1}, function(data, headersFun){
  console.log(data, headersFun());
})

See this fiddle. Hope this helps !!!

like image 40
vinesh Avatar answered Oct 29 '22 05:10

vinesh


Old question, but i think it's worth mentioning for the future reference. There is 'official' solution for this in angular documentation:

It's worth noting that the success callback for get, query and other methods gets passed in the response that came from the server as well as $http header getter function, so one could rewrite the above example and get access to http headers as:

var User = $resource('/user/:userId', {userId:'@id'});

var users = User.query({}, function(users, responseHeaders){
  // ...
  console.log(responseHeaders('x-app-pagination-current-page'));
});

(code from docs slightly updated for clarity)

For CORS requests, exposing headers as mentioned in other answers is required.

like image 6
rastasheep Avatar answered Oct 29 '22 05:10

rastasheep