admin管理员组

文章数量:1379736

I have an angular $resource for login and getting user's info. The login sends the username and password to server and gets a Bearer token. In the success function of User.login the token is stored in localStorage. In getEmail, I'm including the token in header to the user's email address.

The problem is, the first time getEmail is called in controller, $window.localStorage.getItem('TK') evaluates to null but if I refresh the page then it works correctly. All of the subsequent requests to the server that have the token included work as expected. What could cause this?

Not to mention, getEmail is called way after login and I have confirmed that the token is present in localStorage before the getEmail is called.

angular.module('authentication')
    .factory('User', function ($resource, $window) {
        return $resource('/login', {}, {
            login: {
                method: 'POST'
            },

            getEmail: {
                url: '/user',
                method: 'GET',
                headers: {
                    'Authorization': "Bearer " + $window.localStorage.getItem('TK')
                }
            }
        });
    })

In response to @ ment: My controller looks like this:

angular
        .module('app.mymodule', ['ngReource', 'authentication')
        .controller('myCtrl', mymodule);

    mymodule.$inject = ['User', '$window'];

    function mymodule(User, $window) {

        // THIS PRINTS THE TK IN CONSOLE CORRECTLY
        console.log($window.localStorage.getItem("CHTOKEN"));

        // THIS IS UNAUTHORIZED CUZ TK IS NULL
        User.getEmail({}, function(data){
                console.log('set the email');
        });
    }

I have an angular $resource for login and getting user's info. The login sends the username and password to server and gets a Bearer token. In the success function of User.login the token is stored in localStorage. In getEmail, I'm including the token in header to the user's email address.

The problem is, the first time getEmail is called in controller, $window.localStorage.getItem('TK') evaluates to null but if I refresh the page then it works correctly. All of the subsequent requests to the server that have the token included work as expected. What could cause this?

Not to mention, getEmail is called way after login and I have confirmed that the token is present in localStorage before the getEmail is called.

angular.module('authentication')
    .factory('User', function ($resource, $window) {
        return $resource('/login', {}, {
            login: {
                method: 'POST'
            },

            getEmail: {
                url: '/user',
                method: 'GET',
                headers: {
                    'Authorization': "Bearer " + $window.localStorage.getItem('TK')
                }
            }
        });
    })

In response to @ ment: My controller looks like this:

angular
        .module('app.mymodule', ['ngReource', 'authentication')
        .controller('myCtrl', mymodule);

    mymodule.$inject = ['User', '$window'];

    function mymodule(User, $window) {

        // THIS PRINTS THE TK IN CONSOLE CORRECTLY
        console.log($window.localStorage.getItem("CHTOKEN"));

        // THIS IS UNAUTHORIZED CUZ TK IS NULL
        User.getEmail({}, function(data){
                console.log('set the email');
        });
    }
Share Improve this question edited Feb 11, 2015 at 1:18 Sam R. asked Feb 11, 2015 at 0:08 Sam R.Sam R. 16.4k14 gold badges73 silver badges125 bronze badges 5
  • 1 Just to know if that's an angular issue, what happens if you use the regular window instead of $window? – floribon Commented Feb 11, 2015 at 0:54
  • @floribon, just tried it. Same problem. – Sam R. Commented Feb 11, 2015 at 0:59
  • 1 So this is not related to angular. Somehow you don't have the data in your localStorage even if you think you do. Can you log window.localStorage.getItem('TK') even before running any angular code? If it is null, then angular will not help. – floribon Commented Feb 11, 2015 at 1:09
  • @floribon, I have updated my question. I have logged the token just before calling the getEmail and it correctly prints it to the console. So the Token is actually there. I can even see it in my FF DevTool. – Sam R. Commented Feb 11, 2015 at 1:19
  • 1 You are first logging the CHTOKEN item. Then in your getEmail function you are checking for TK. These are two different items, so nothing shows that TK does exist before the call to getEmail. If it still does, it means somewhere you erase the value, either with localStorage.removeItem or localStorage.clear – floribon Commented Feb 11, 2015 at 1:22
Add a ment  | 

1 Answer 1

Reset to default 4

Your problem is that the resource definition is provided at the time of creation (before you have saved a token).

You can either add a general request interceptor to the $httpProvider so all requests are covered or change your getEmail action's header to use a function so it is evaluated at run time, eg

headers: {
    'Authorization': function() {
        var token = $window.localStorage.getItem('TK');
        return token ? 'Bearer ' + token : null;
    }
}

本文标签: javascriptAngularJS quotlocalStoragegetItemquot is null in resourceStack Overflow