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?
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?
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
headersGetter
function that gets passed as a second parameter after your data. See the answer below or here: docs.angularjs.org/api/ngResource/service/$resource –
Speer @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 !!!
then
function - I almost missed this because of your cross-domain info! –
Speer get
call with callbacks for success and error, and in that case the headersFun exists. But handling the response via $promise.then
as you wrote above has no such second parameter - headersFun
is undefined. –
Cuda 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.
© 2022 - 2024 — McMap. All rights reserved.