AngularJS:从控制器访问连接的用户信息

时间:2016-08-25 17:58:53

标签: angularjs service controller

我在这里与AngularJS斗争并访问连接的用户信息。我的目标是在服务中保存已连接用户的信息,以便在整个应用程序中可用。所以我就是这样做的:

登录功能通过登录服务公开,其代码如下:

(function(){
var $loginService = angular.module("RockMyTask.LoginService", [
    "satellizer",
    "RockMyTask.ApiService"
]);

/**
 * Login service
 *
 * function login(identifier, password, after)
 *  Logs the given user. Global data about the user are registered in the root scope.
 *  @param identifier The user's identifier (either email or password)
 *  @param password The user's password
 *  @param success (optional) A callback to execute when the user is successfully logged in. This callback is passed
 *  the response object.
 *  @param failure (optional) A callback to execute when the log in fails. This callback is passed the response
 *  object.
 *
 * function restore()
 *  If the user was already logged in, restore the user data in the rootScope.
 *
 * function connectedUser()
 *  Return the data of the currently connected user. If the user is not connected an empty object is returned.
 *  If the user data hasn't be fetched yet, then an empty object is returned and this object will be filled with
 *  the user data as soon as it is received.
 */
$loginService.factory("Login", ["$auth", "$rootScope", "User",
    function($auth, $rootScope, User) {
    var obj = {};
    var connectedUser = {};

    obj.logout = function() {
        $auth.logout();
        //Authorization.clear();
        connectedUser = null;
    };

    obj.login = function(identifier, password, success, failure) {
        var credentials = {
            user_identifier: identifier,
            password: password
        };

        $auth.login(credentials).then(function(auth_response) {
            // fetch user data (with both spectator and rockstar flags set to true)
            User.me(true, true).then(function(response) {
                connectedUser = response.data;
                //TODO add check for DEBUG_MODE
                console.log("Received connected user data and stored it in connectedUser var");
            }, function() {
                connectedUser = {};
            });

            // execute provided success callback
            if (_.isFunction(success)) {
                success(auth_response);
            }
        }, function(response) {
            connectedUser = null;

            // execute provided failure callback
            if (_.isFunction(failure)) {
                failure(response);
            }
        });
    };

    obj.restore = function() {
        if ($auth.isAuthenticated()) {
            User.me(true, true).then(function(response) {
                connectedUser = response.data;
            }, function() {
                connectedUser = null;
            });
        } else {
            connectedUser = null;
        }
    };

    obj.getConnectedUser = function(){
        if($auth.isAuthenticated && !connectedUser){
            User.me(true, true).then(function(response) {
                connectedUser = response.data;
            }, function() {
                connectedUser = null;
            });
        }
        return connectedUser;
    };

    obj.updateUserInfo = function(user){
        connectedUser = user;
    };

    obj.isConnectedUserRockstar = function(){
        return connectedUser.rocker != null;
    };
    obj.isConnectedUserSpectator = function(){
        return connectedUser.spectator != null;
    };

    return obj;
}]);
})();

正如您在代码中观察到的那样,在成功登录后,我会启动一个HTTP请求(User.me(true, ture)),然后将返回的数据(表示有关已连接用户的信息)存储在服务的即席变量中{ {1}}。

要从应用程序的任何位置访问连接的用户信息,我在Login服务中实现了一个名为connectedUser的功能,其代码在此处报告:

getConnectedUser

此函数检查用户是否确实已经过身份验证,并且变量connectedUser是否已经正确填充,如果没有,它会再次触发HTTP函数来检索数据(否则它只返回obj.getConnectedUser = function(){ if($auth.isAuthenticated && !connectedUser){ User.me(true, true).then(function(response) { connectedUser = response.data; }, function() { connectedUser = null; }); } return connectedUser; }; var)。 / p>

现在,我的问题如下。在成功登录后,我将用户重定向到的页面使用了我已通过登录服务的控制器。控制器尝试检索连接的用户信息,但结果是空指针。我做错了什么?

控制器中的代码(以防万一,即使非常简单):

connectedUser

编辑1 在浏览器中查看控制台,我看到HTTP请求成功,返回的数据是:

$scope.user = Login.getConnectedUser();

如前所述,当我尝试访问控制器中{"id":3,"email":"iCartwright@hotmail.com","name":"Michele","surname":"Imperiali","locale":"it_IT","picture":"https:\/\/storage.rockmytask.it\/users\/profile_image\/3.jpeg","birthday":"1982-06-23","gender":"M","country":"IT","province":"Lombardia","city":"Milano","zip":"20100","street":"190 Grover Expressway","mobile_phone":"(437)924-8282","home_phone":"239-250-3166x783","username":"spectator","validated":true,"timezone":"Europe\/Rome","created_at":"2016-04-01T12:50:53+0000","rocker":null,"spectator":{"description":"I need help with my garden !"}} 的变量时,我得到一个空指针异常。

1 个答案:

答案 0 :(得分:-1)

我认为这个问题与

有关
, function() {
            connectedUser = null;
        }

您是否有理由将connectedUser设置为null?如果原因是因为如果从后端收到错误或者返回错误,则要将其设置为null,然后执行:

obj.getConnectedUser = function(){
    if($auth.isAuthenticated && !connectedUser){
        User.me(true, true).then(function(response) {
            connectedUser = response.data;
        }, function(error) {
            connectedUser = null;
        });
    }
    return connectedUser;
};

如果你得到一个错误的响应,那么这只会将connectUser设置为null。截至目前,看起来connectUser总是设置为null并解释你的空指针。