Reputation: 8478
Suppose I have an angular app called chococalateApp
that depends on 3 other modules, namely Product
, Sales
and LogIn
.
Now, my app is building on RESTful API. Upon successful login, the server will respond by sending back an authentication token. I would like to append this token as a custom header X-AUTH
whenever $http
services are used. Since all my REST API requires the auth token, I would need to append this header in every $http
request. This is doable by configuring the $httpProvider, as shown below:
angular.module('chocolateApp',['Product','Sales','Login'])
.config(['$httpProvider', function($httpProvider){
$httpProvider.defaults.headers.common['X-AUTH'] = 'randomkeybyserver'
}
])
My question is, can I inject the value of the auth-token AFTER the module has been bootstrapped?
For example, I have a service in LogIn
module that is able to do the authentication, and retrieved the required token. How do I pass the token back to my main chocolateApp
module and configure it? Will this result in circular dependency, or is it that my understanding of DI is wrong here?
If this is not achievable, how should this be designed?
Upvotes: 0
Views: 93
Reputation: 10114
You can do it from your Login
service after authentication and it will be available across your app.
login: function(...) {
$http.post(...).then(function(response) {
$http.defaults.headers.common['X-AUTH'] = response.data.randomkeybyserver;
});
}
Upvotes: 0