Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS. Set default header depending on current route

Tags:

angularjs

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?

like image 762
Fyodor Khruschov Avatar asked Feb 22 '26 13:02

Fyodor Khruschov


1 Answers

$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

like image 119
Poyraz Yilmaz Avatar answered Feb 24 '26 03:02

Poyraz Yilmaz