Angular JS Factory Variables未定义

时间:2016-12-22 15:45:40

标签: javascript angularjs

我一直在尝试使用Angular JS创建一个从PHP API获取会话数据的脚本来创建身份验证。

我创建了一个名为User的工厂,在我的loginController我使用User.Initialise()来检查PHP中的会话是否附加了user_id

在我的User.Initialise()中使用loginController时(我的会话中只有一个用户连接了它),它将使用$location.path("/dashboard")更改到仪表板的路由。仪表板路由有一个控制器,其变量$scope.UserID使用User.Session.user_id分配,但是,当我尝试调用User.Session时,它返回undefined,即使User.Initialise();指定它在loginController

有人可以对此有所了解吗?

var $Gladium = angular.module("Gladium", ["ngRoute", "ngAnimate", "ngSanitize"]);

$Gladium.config(function($routeProvider, $locationProvider){

    $routeProvider.when("/",{
        templateUrl: "pages/login.html",
        controller: "loginController"
    }).when("/dashboard",{
        templateUrl: "pages/dashboard.html",
        controller: "dashboardController"
    }).when("/error/:error_code", {
        templateUrl: "pages/system_error.html",
        controller: "errorController"
    });

});

/* Controllers */
$Gladium.controller("dashboardController", function($scope, User){
    console.log("Services:");
    console.log(User.Session);

});
$Gladium.controller("loginController", function($scope, $location, User){

    User.Initialise().then(function(){
        $scope.Authenticate = true;
        if(User.loggedIn()){
            $location.path("/dashboard");
        }
    });

    /* Variables */
    $scope.Email;
    $scope.Password;

    $scope.Login = function(){
        if(User.logIn($scope.Email, $scope.Password)){
            $location.path("/dashboard");
            return true;
        }
    }



});
$Gladium.controller("errorController", function($scope, $routeParams){

    $scope.Errors = {
        "request": "We couldn't process that request at this time. Please try again later.",
        "unknown": "An unknown error occurred if this is persistant please contact technical support."
    };

    $scope.currentError =  $scope.Errors[$routeParams["error_code"]];

});

/* Factories */
$Gladium.factory("User", function($http, $location){

    var Session;
    var Error;

    return {

        Initialise: function(){
            return $http.get("core.php?do=getSession").then(function(requestData){

                if(requestData.data["requestStatus"] == 1){
                    Session = requestData.data.data;
                }else{
                    $location.path("/error/request");
                    return false;
                }

            });
        },


        loggedIn: function(){
            if(Session["user_id"] != 0){
                return true;
            }else{
                return false;
            }

        },

        logOut: function(){
            if(Session["user_id"] != 0 ){
                $http.post("core.php",{
                    do: "logout"
                }).then(function(requestData){
                    if(requestData.data["requestStatus"] == 1){

                    }else{

                    }
                });
            }else{
                console.warn("There is no user session to logout.");
            }
        },

        logIn: function(Email, Password){
            $http.post("core.php",{
                do: "login",
                email: Email,
                password: Password
            }).then(function(requestData){
                if(requestData.data["requestStatus"] == 1){

                    Data = requestData.data;

                    if(Data["actionStatus"] == 1){
                        Initialise();
                    }else{
                        Error = Data["Error"];
                        return false;
                    }

                }else{
                    $location.path("/error/request");
                    return false;
                }

                $location.path("/error/unknown");
                return false;
            });
        }

    }

});

1 个答案:

答案 0 :(得分:1)

我认为你只是忘记返回Session变量,该变量应该是User服务的属性

....
$Gladium.factory("User", function($http, $location){

var Session;
var Error;

return {
    // return the Session so it can be accessed via User.Session, or it is a variable in private closure
    Session:Session
    Initialise: function(){
        return $http.get("core.php?do=getSession").then(function(requestData){

            if(requestData.data["requestStatus"] == 1){
                Session = requestData.data.data;
            }else{
                $location.path("/error/request");
                return false;
            }

        });
    },
....

更新

很抱歉,上面的更改无法解决您的问题,因为您分配的Session关闭变量不会更改User.Session。这样它仍然是未定义的。

有几种方法可以解决这个问题。

我认为最简单的方法是保持Session私有并通过get函数User.getSession()访问它。

$Gladium.factory("User", function($http, $location){

var Session;
var Error;

return {
// use get function to get Session
getSession:function(){
  return Session;
},
Initialise: function(){
    return $http.get("core.php?do=getSession").then(function(requestData){

        if(requestData.data["requestStatus"] == 1){
            Session = requestData.data.data;
        }else{
            $location.path("/error/request");
            return false;
        }

    });
},
....

通过这种方式,您可以Session访问User.getSession()