Reputation: 1717
I need to set default header in $http service depending on current route. This is the code:
$http.defaults.headers.common.HeaderName = 'HeaderValue';
I need to watch current $location.path
and change value of the header according the route.
Can I put this code in $routeProvider section? Something like:
$routeProvider
.when('/route', {
templateUrl: 'book.html',
controller: 'BookController',
resolve: function() {
//set default header here
}
})
What is the proper way to do that?
Upvotes: 3
Views: 2470
Reputation: 5857
$routeProvider
is a provider, but on the other hand $http
is an instance, so basically you cannot inject an instace to config block where you set $routeProvider
, but you can inject $http instance to run block which suits you most...
ok let's deal the problem you face, actually you can do it any controller you want but you want it to do when only location/route changes so let's inject another instance $rootScope to run block to watch location/route changes...
but you have one more request set $http.defaults
depends on $location.path()
so let's inject another instance $location
to run block to get current path...
so here is our final run block
app.run(function($rootScope, $http, $location) {
$rootScope.$on('$locationChangeSuccess', function(event, next, current) {
$http.defaults.headers.common.HeaderName = $location.path();
console.log("Headers :",$http.defaults.headers);
});
});
from now on after every location change trigger our watch where we set $http.headers
depends on $location.path()
...
here is working PLUNKER
UPDATE
if you want to look other $route
and $location
events check this PLUNKER
Upvotes: 3
Reputation: 33554
You could change the header based on location by listening to the $routeChangeStart
event, and changing the defaults there:
$rootScope.$on( '$routeChangeStart', function() {
$http.defaults.headers.common.headerName = 'Path is ' + $location.path();
});
Upvotes: 0