9

All of our content pages have a particular header, X-Foo. When the content of the ng-view changes, we want to display the new page's X-Foo header in a different element. How can we get this value whenever the content changes?

EDIT: Since this was apparently unclear, the header is expected in the response, not the request.

user1207177
  • 577
  • 3
  • 16
  • When the content changes or when the route changes? `ngView` has a `$viewContentLoaded` event that you could hook onto. Alternatively there's the `$routeChangeSuccess` event if you'd like to hook into when the route changes. – Ankh Mar 02 '17 at 16:21
  • @Ankh Either one is fine. However, I assume that, at the point the route changes, the new data has not come in yet, so there is no response from which to get the headers. – user1207177 Mar 02 '17 at 17:19

2 Answers2

4

You can use a httpInterceptor for this. HTTP interceptors are a great way to define behavior in a single place for how a request or response is handled for all HTTP calls using the $http service

app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('httpInterceptor');
}).factory('httpInterceptor', function (liveInterviewConfiguration) {
    return {
        request : function (request) {
            console.info("Your request headers are");
            console.info(request.headers);
            return request;
        },
        requestError : function (error) {
            return error;
        },
        response : function (response) {
            return response;
        },
        responseError : function (error) {
            return error;
        }
    };
});
Pramod_Para
  • 671
  • 3
  • 10
0

Can you access the headers in the controller with $http? I've nothing that has changing headers readily available to test this with.

controller('SampleCtrl', function($http, $scope) {
    // Add headers from $http
    $scope.http = $http.defaults.headers.common;
});

Alternatively, if that does not work, you may want to look at using http interceptors.

.config(function($routeProvider, $locationProvider, $httpProvider) {

    $httpProvider.interceptors.push(function($q) {
        return {
            'response': function(response) {
                // do something on success
                console.log(response);
                return response;
            }
        };
    });
}
Brian
  • 4,921
  • 3
  • 20
  • 29