Restangular: How to get HTTP response header?

Issue

I have a REST server which returns a Link HTTP header with a response to a PUT to indicate the URL of the newly-created entity:

Link:<entities/6>; rel="created"

Is there any possibility to read that link header with Restangular?

The only facility to intercept HTTP requests with Restangular I’ve met so far is to register a response interceptor in the app config:

restangular.addResponseInterceptor(function (data, operation, what, url, response, deferred) {
    console.log(response.headers())
    return response.data;
});

However, with above demo implementation in place, the only HTTP header which gets logged is content-type. Still, I can see in the browser development toolbar that a response comes indeed with many additional HTTP response headers, such as Server, Date, and the aforementioned Link.

Why do I not have access to the full array of HTTP response headers through addResponseInterceptor()? Is there any way to capture the HTTP response header in question using Restangular?

Note: I don’t search for an answer using HAL or any other special response body format. I would rather like to know whether I can use plain HTTP headers with Restangular or not (if not, I will probably resort to HAL or something).

Solution

You don’t need a ResponseInterceptor to do this. You just need to set fullResponse to true to get the whole response (including the http headers) every time you do any request.

Restangular.setFullResponse(true);

You can set it globally in your app configuration. Something like this:

angular.module('YourApp')
     .config(['RestangularProvider',
       function (RestangularProvider) {
         RestangularProvider.setFullResponse(true);
...

Then, every time you receive a response, you can access all the response headers.

Restangular.all('users').getList().then(function(response) {
    $scope.users = response.data;
    console.log(response.headers);
}

Example:

response.headers('Link')

NOTE: Be careful because using fullResponse, the response data is located in response.data, not directly in response.

EDIT: As @STEVER points, you also need to expose the headers in your server API.
Example:

Access-Control-Expose-Headers: Link

You can get more detailed information in Restangular documentation

Hope it helps.

Answered By – troig

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.