Example for Stackoverflow. Added default header
by Stepan Kasyanenko
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="ExampleController as vm">
<pre>Steps:
1) Press "Start Request" button and check in console header
2) Press "Simulate auth" button. This is add default header "myToken"
3) Press "Start Request" button and check in console header "myToken".
</pre>
<button ng-click="vm.start()">
Start Request
</button>
<button ng-click="vm.auth()">
Simulate auth
</button>
</div>
</div>
JavaScript
angular.module('ExampleApp', [])
.controller('ExampleController', function(ExampleService,AuthService) {
var vm = this;
vm.start = function(){
ExampleService.getData();
};
vm.auth = function(){
AuthService.auth();
}
})
.service('ExampleService', function($http) {
return {
getData: function() {
return $http.get("/urlsource");
}
}
}).service('AuthService', function($http) {
return {
auth: function() {
return $http.get("/auth")
.then(function(apiResponse){
//after success auth add token
$http.defaults.headers.common['myToken']=apiResponse.data;
})
.catch(function(){
// just for example in jsfiddle, because we got 404 error for request `auth` url
$http.defaults.headers.common['myToken']='12314dsfsfsd';
});
}
}
});