必须登录两次:angular js



我遇到了这个问题的解决方案,但我可能没有正确实现它,或者它不是解决方案。问题是,我需要登录两次。我尝试使用$scope.$apply(),但我不知道我是否使用它是正确的。我的登录控制器:

app.controller('loginctrl',['$rootScope','$scope','$http','$state','$cookies',function($scope,$rootScope,$http,$state,$cookies){
var cookietoken= $cookies.get('Token');
if(cookietoken)
{
    alert('You are already logged in!');
    $state.go('home');
}
else
{
    $scope.user={
        username:"",
        password:"",
        rememberme:""
    };
    $scope.showerror=false;
    $scope.login = function(){
        $http({
            method:"POST",
            url:$rootScope.apiend+'login',
            data:$scope.user
        })
        .success(function(result){
            console.log(result);
        }).error(function(){
            alert('something looks wrong.');
        });
    };
}

}]);

编辑:页面第一次进入error方法,第二次显示success方法

我只是猜测,但我假设当login函数被调用时,它成功地将您登录"在服务器部分",但客户端的success方法只不过是在控制台中写入结果,当您第二次尝试时,它检查您已经登录(检查cookietoken),如果是这样,将您发送到"主页"页。

如果是这种情况,那么您只需要在登录成功后在success方法中添加$state.go('home');行:

app.controller('loginctrl',['$rootScope','$scope','$http','$state','$cookies',function($scope,$rootScope,$http,$state,$cookies){
var cookietoken= $cookies.get('Token');
if(cookietoken)
{
    alert('You are already logged in!');
    $state.go('home');
}
else
{
    $scope.user={
        username:"",
        password:"",
        rememberme:""
    };
    $scope.showerror=false;
    $scope.login = function(){
        $http({
            method:"POST",
            url:$rootScope.apiend+'login',
            data:$scope.user
        })
        .success(function(result){
            console.log(result);
            $state.go('home');              /* <--  add this line here */
        });
    };
}
}]);

最新更新