Issue
I'm very new to Angular, so it's perfectly possible I made some stupid mistakes.
What I'm trying to do is use a token that is saved in localStorage and put that in all requests.
I have this code block:
.config(['$httpProvider', 'localStorageService', function($httpProvider, localStorageService) {
//Http Interceptor to check auth failures for xhr requests
$httpProvider.interceptors.push('authHttpResponseInterceptor');
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common.Authorization = 'Token token=' + localStorageService.get("TemponiaToken")
}])
And I'm getting this error message:
Uncaught Error: [$injector:modulerr] Failed to instantiate module starter due to:
Error: [$injector:unpr] Unknown provider: localStorageService
I found this question and answer which (I think) explains the problem: Why can't I use the localStorage in my .config when it's include in the .module definition?
However: how can I solve this? Change the .config into .run ? Thanks for any pointers in the right direction.
Solution
As the answer you found says is not possible to inject services during the config phase.
There are two possible solution to your problem.
The first one is to use the native localStorage
object
localStorage.getItem("TemponiaToken") // it just works without injecting any service
The other one is to correctly define the interceptor
yourApp.factory('AuthInterceptor', function (localStorageService) {
return {
request: function (config) {
config.headers = config.headers || {};
config.headers.Authorization = 'Token token=' + localStorageService.get("TemponiaToken")
return config;
}
};
});
yourApp.config(function ($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
});
Answered By - marquez
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.