Updating AngularJS HTTP Common Headers at Runtime

How can I update common HTTP headers at runtime from an AngularJS controller, for example? $httpProvider.defaults.headers.common['Authorization'] ? It seems that $httpProvider is only accessible from the configuration module, but I need to update the general HTTP headers for all future requests from the controller or the service called by the controller.

I can update the local scope headers for the next request by entering $http in my controller, but I need to update the HTTP headers for all future requests, in particular for basic authentication.

+4
source share
2 answers

Not sure when it appeared in Angular, but after 20 months you can define default headers at runtime directly on the $ http object.

From $ http documentation : setting up HTTP headers

 $http.defaults.headers.common.Authorization = 'Basic dXNlcjpwYXNzd29yZA==' 
+2
source

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

Here is 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

+1
source

Source: https://habr.com/ru/post/1490287/


All Articles