return 工厂错误
return error from factory
我是 Angular JS 的新手。我正在尝试 return 使用 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;
}]);
您必须使用 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