Abhishek Kulshrestha Abhishek Kulshrestha - 1 year ago 60
AngularJS Question

How to update headers in $resource when routing to a new state

I'm trying to implement JWT token in this project. For that I used Authorization header in the

$resource
, like as this.

When I login on UI state "A", after getting logged in, I put the token in the localStorage as

$localStorage.token = data.token;


When I go to UI state "B" of the page, it uses the following service and send a request with no token. But on refreshing the page, it sends the same request with the token.

angular.module('BlurAdmin')
.factory('valueService', ['Token','$localStorage','$resource', 'endpoint', function(Token,$localStorage, $resource, endpoint) {
return {
getValues: $resource(endpoint + '/admin/getvalues', null, {
'get': {
method: 'GET',
headers:{'Authorization':'Bearer '+$localStorage.token}
}
}),
}
}]);


I think the service stores the
$localStorage.token
value initially and uses that even when the state changes. But when the page is reloaded, it gets the
$localStorage.token
value again.

How do I force this service to get the
$localStorage.token
value everytime the UI state changes?

Thanks in Advance!

lin lin
Answer Source

Your problem is that the resource definition is provided at the time of creation (before you have saved a token). To avoid this behavior, simply create a wrapper function and parse your token into it.

angular.module('BlurAdmin')
    .factory('valueService', ['Token','$localStorage','$resource', 'endpoint', function(Token,$localStorage, $resource, endpoint) {
        return function (token) {
            return $resource(endpoint + '/admin/getvalues', {}, {
                get: {
                    method: 'GET',
                    headers:{'Authorization':'Bearer ' + token}
                }
            })
        }
    }]);

Call your factory function like:

valueService($localStorage.token).get(function (result) {
    console.log(result);
}, function (error) {
    console.log(result);
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download