AngularJS" localStorage.getItem"在$资源空 [英] AngularJS "localStorage.getItem" is null in $resource

查看:220
本文介绍了AngularJS" localStorage.getItem"在$资源空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个角 $资源用于登录,获取用户的信息。登录发送用户名和密码的服务器并得到一个承载令牌。在成功功能 User.login 标记存储在的localStorage 。在 getEmail ,我包括头令牌到用户的电子邮件地址。

问题是,在第一时间 getEmail 被称为控制器, $ window.localStorage.getItem('TK')计算结果为,但如果我刷新页面,则可以正常工作。所有后续请求已经令牌包括按预期方式工作的服务器。这是什么原因?

更何况, getEmail 被称为方式登录后,我已经证实,令牌处于的localStorage getEmail 被调用。

  angular.module('验证')
    .factory(用户,函数($资源,$窗口){
        返回$资源('/登录',{},{
            登录: {
                方法:POST
            },            getEmail:{
                网址:'/用户,
                方法:GET,
                标题:{
                    授权:旗手+ $ window.localStorage.getItem(TK)
                }
            }
        });
    })

在回应@评论:
我的控制器看起来是这样的:

 
        .module('app.mymodule',['ngReource','验证')
        .controller('myCtrl',MyModule的);    。MyModule的$注射= ['用户','$窗口'];    功能MyModule的(用户,$窗口){        //将打印出TK控制台正确
        的console.log($ window.localStorage.getItem(CHTOKEN));        //这是未经授权的CUZ TK IS NULL
        User.getEmail({}功能(数据){
                的console.log('设置电子邮件');
        });
    }


解决方案

您的问题是,资源定义是在创建时所提供的(已保存令牌之前)。

您可以添加一般的请求拦截 $ httpProvider 那么所有请求都被覆盖或修改你的 getEmail 操作的使用函数所以它在运行时进行评估,如:

 标题:{
    '授权':功能(){
        VAR令牌= $ window.localStorage.getItem('TK');
        返回令牌? 承载+令牌:空;
    }
}

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

解决方案

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

这篇关于AngularJS" localStorage.getItem"在$资源空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆