AngularJS “localStorage.getItem” is null in $resou

2019-02-25 11:57发布

问题:

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 @ comment: 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');
        });
    }

回答1:

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;
    }
}