从工厂返回错误

时间:2015-02-20 12:56:26

标签: angularjs firebase firebasesimplelogin

我是Angular JS的新手。我尝试使用Firebase简单登录从工厂返回错误回到控制器。有人可以帮忙吗???

registrationController.controller('RegistrationController', [ '$scope' ,'$rootScope', '$firebase', '$location' , 'FIREBASE_URL' , 'Authentication',
function($scope , $rootScope , $firebaseSimpleLogin, $location, FIREBASE_URL, Authentication, ) {

    $scope.login = function() {
        Authentication.login($scope.user);
        console.log(error);
        $scope.message = error
    } //login

    }// end of function

]);//RegistrationController


authenticationController.factory('Authentication' , ['$firebase' , '$location' , 'FIREBASE_URL', '$rootScope' , function( $firebaseSimpleLogin , $location, FIREBASE_URL, $rootScope){

var ref = new Firebase(FIREBASE_URL);

var myObject = {
    login : function(user){
   return ref.authWithPassword({
          email    : user.email,
          password : user.password
        }, function(error, authData) {
        if (error) {
           var error = error
           console.log('error');
           return error;
        } else {
            console.log("SUCCESS");
            // $rootScope.$evalAsync($location.path('/meetings'));
          }
        }); 
    }, // login

} // object

return myObject; 

}]);

1 个答案:

答案 0 :(得分:1)

您必须使用deferred和promise,因为身份验证是异步任务:

authenticationController.factory('Authentication' , ['$firebase' , '$location' , 'FIREBASE_URL', '$rootScope' , '$q', function( $firebaseSimpleLogin , $location, FIREBASE_URL, $rootScope, $q){

var ref = new Firebase(FIREBASE_URL);

var myObject = {
    login : function(user){
 var defered = $q.defer();
 ref.authWithPassword({
          email    : user.email,
          password : user.password
        }, function(error, authData) {
        if (error) {
           defered.reject(error);
        } else {
            defered.resolve(authData);
          }
        }); 
        return defered.promise;
    }, // login

} // object

return myObject; 

在控制器中使用承诺:

registrationController.controller('RegistrationController', [ '$scope' ,'$rootScope', '$firebase', '$location' , 'FIREBASE_URL' , 'Authentication',
function($scope , $rootScope , $firebaseSimpleLogin, $location, FIREBASE_URL, Authentication, ) {

    $scope.login = function() {
        Authentication.login($scope.user).then(function(authData){
          //use authData
        }, function(error){
          console.log(error);
          $scope.message = error
        });

    } //login

    }// end of function

]);//RegistrationController