0

第一次打电话,authenticated属性是false,连证件都OK。如果我再次使用相同的凭据登录,就可以了。

无论如何,我不确定我下面的工厂在 angularjs 中是否正确。你能给我一些建议吗?

工厂:

app.factory('authenticatorService',['$resource', function($resource){
    var authenticator = {};

    authenticator.attempt = function(email, password){
        var current = this;
        $resource("/service/authentication/:id",null,{'update' : { method: 'PUT'}})
            .save({'email' : email,'password': password},
                //success
                function(response){
                    current.authenticated = sessionStorage.authenticated = true;
                    current.userinfo = response.user;
                    current.authenticated = true;
                },
                function(response){
                    current.authenticated = false;
                }
            );
        return  this.authenticated;
    };
    authenticator.logout = function(){
        delete sessionStorage.authenticated;
        this.authenticated = false;
        this.userinfo = null;
        return true;
    };
    authenticator.check = function(){
        if(this.userinfo && this.authenticated){
            return true;
        }
        return false;
    };

    return authenticator;

}]);

控制器:

app.controller('authenCtrl',
[
'authenticatorService',
'$scope',
'$sanitize',
'$log',
'$location',
function(alert, authenticator, $scope, $sanitize, $log, $location){

    $scope.login = function(){

        if(authenticator.attempt($sanitize($scope.email) ,$sanitize($scope.password))){
            $location.path('/dashboard');
        }else{
            alert.add("danger","Login fail.");
        }
    }
}]);
4

1 回答 1

1

this.authenticatedin将authenticator.attempt在异步调用$resource完成之前返回。

在从工厂返回之前,以及在控制器中接收之前,您需要等待 promise 解决。

这样的事情应该会起作用:

工厂:

authenticator.attempt = function(email, password){

  var current = this;

  $resource("/service/authentication/:id", null, {'update' : { method: 'PUT'}})
    .save({'email' : email,'password': password},
      function(response){
          current.authenticated = sessionStorage.authenticated = true;
          current.userinfo = response.user;
          current.authenticated = true;
      },
      function(response){
          current.authenticated = false;
      }
    ).$promise.then(function () {
      return current.authenticated;
    });
};

控制器:

$scope.login = function() {

  var email = $sanitize($scope.email);
  var password = $sanitize($scope.password);

  authenticator.attempt(email, password).then(function(isAuthenticated) {

    if (isAuthenticated) $location.path('/dashboard');
    else alert.add("danger", "Login fail.");

  });
};
于 2014-05-07T07:27:31.287 回答