Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can I update the common HTTP headers at runtime from an AngularJS controller, e.g. $httpProvider.defaults.headers.common['Authorization']? It seems $httpProvider can only be accessed from a config module, but I need to update common HTTP headers for all future requests from a controller, or a service called by the controller.

I can update the locally scoped headers for the next request by injecting $http into my controller, but I need to do update HTTP headers for all future requests, specifically for basic authentication.

share|improve this question
Can't you just store in the service that makes all the http request the authorization to use and add them to all future request ? – jackdbernier 2 days ago
@jackdbernier, AFAIK I can store an auth token in a Session service, but then I have to inject that service into every controller that does an HTTP request and set the common $http Authorization header many times. And somewhere I will forget. Can you provide any code samples? – pate 2 days ago
I was thinking about wrapping your http request inside a Service. Then instead of injecting $http in your controllers/services you can inject your http wrapper. In this service you could have a method to set the authorization. – jackdbernier yesterday

1 Answer

I used this strategy once when I had to work with an API. I created an XYZApiService to wrap all the requests to that API.

Here's a simple example:

var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope, HttpWrapper) {
  $scope.movies = [];
  HttpWrapper.setAuthorization('Basic dXNlcjpwYXNzd29yZA==');
  HttpWrapper.http({
    method: 'get',
    url: 'movies.json'
  }, function(data, status){
    $scope.movies = data;
  }, function(data, status){
    console.log('error', data, status);
  })
});

app.run();

app.factory('HttpWrapper', function($http) {
  var authorization = null;
  return {
    setAuthorization: function(auth){
      authorization = auth;
    },
    http: function(options, successCallback, errorCallback){
      if(authorization){
        options.headers = options.headers || {};
        options.headers.authorization = authorization;
      }
      console.log(options);
      $http(options).success(successCallback).error(errorCallback);
    }
  }
});

You can try it in Plunker here:

http://plnkr.co/edit/hr2Rvojic0asvWxSoalo?p=preview

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.