Get headers when ng-view changes
Asked Answered
A

2

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.

Aspirate answered 2/3, 2017 at 16:6 Comment(2)
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.Rhpositive
@Rhpositive 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.Aspirate
S
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;
        }
    };
});
Starcrossed answered 17/3, 2017 at 4:10 Comment(0)
C
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;
            }
        };
    });
}
Contractor answered 17/3, 2017 at 3:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.