在AngularJS中将认证错误从工厂传递给控制器
我试图通过工厂实现Firebase身份验证,我希望将错误甚至authData对象从工厂传递回控制器。这可能吗?我似乎不知道该怎么做。我不断得到未定义的变量 如果在登录到console.log失败时打印错误,我会得到预期的结果,因此此代码的其余部分可以正常工作。我只是无法将错误/对象传递回控制器 我的控制器:在AngularJS中将认证错误从工厂传递给控制器,angularjs,Angularjs,我试图通过工厂实现Firebase身份验证,我希望将错误甚至authData对象从工厂传递回控制器。这可能吗?我似乎不知道该怎么做。我不断得到未定义的变量 如果在登录到console.log失败时打印错误,我会得到预期的结果,因此此代码的其余部分可以正常工作。我只是无法将错误/对象传递回控制器 我的控制器: myApp.controller('LoginController', ['$scope', '$location', 'Authentication', function($scope,
myApp.controller('LoginController', ['$scope', '$location', 'Authentication', function($scope, $location, Authentication) {
$scope.login = function() {
Authentication.login($scope.user);
// do something with error from auth factory
}
}]);
$scope.login = function() {
Authentication.login(username, password).then(
function(result) {
$location.path('/stuff');
},
function(result) {
$scope.showLoginErrorMessage = true;
});
};
我的工厂:
myApp.factory('Authentication', ['$firebase', 'FIREBASE_URL', '$location', function($firebase, FIREBASE_URL, $location){
var ref = new Firebase(FIREBASE_URL);
var authObj = {
login: function(user) {
return ref.authWithPassword({
email : user.email,
password : user.password
}, function(error, authData) {
if (error) {
// pass error back to controller
// i've tried the following:
// authObj.err = error;
// return authObj.err = error;
}
else {
// pass authData back to controller
}
});
} // login
};
return authObj;
}]);
也许您可以在控制器中执行此操作:
myApp.controller('LoginController', ['$scope', '$location', 'Authentication', function($scope, $location, Authentication) {
$scope.login = function() {
Authentication.login($scope.user);
// do something with error from auth factory
}
}]);
$scope.login = function() {
Authentication.login(username, password).then(
function(result) {
$location.path('/stuff');
},
function(result) {
$scope.showLoginErrorMessage = true;
});
};
请注意,
then()
将两个函数作为参数(一个表示成功,一个表示错误)。这确实取决于您的身份验证
服务的工作方式,但在我看来还可以。您只需从控制器向工厂传递一个错误处理函数。类似这样(未经测试):