【问题标题】:return error from factory工厂返回错误
【发布时间】:2015-02-20 12:56:26
【问题描述】:

我是 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; 

}]);

【问题讨论】:

    标签: angularjs firebase firebasesimplelogin


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2017-05-10
      • 2012-08-13
      • 2015-02-22
      • 2023-03-23
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多