我正在尝试使用 Angularjs 简化登录功能。我已经分离了 Controller 并制作了一个服务,该服务使用 Firebase 服务器对用户进行身份验证。我应该提到的另一件事是我正在使用他们的 API,称为 Angular Fire。问题是我正在尝试触发 $rootScope.$on 函数。这是代码:
myApp.controller('StatusController', function($scope, $rootScope, $firebase, $firebaseAuth) {
console.log($rootScope);
$rootScope.$on('$firebaseAuth:authWithPassword', function(e, authUser){
console.log("printsomething");
$scope.userEmail = authUser.userEmail;
}); //$firebaseAuth:login
});//StatusController
这是身份验证服务:
myApp.factory('Authentication', function ($firebase, $firebaseAuth, FIREBASE_URL, $location) {
var ref = new Firebase(FIREBASE_URL);
console.log(FIREBASE_URL);
var simpleLogin = $firebaseAuth(ref);
var myObject = {
login: function (user) {
return **simpleLogin.$authWithPassword**({
email: user.email,
password: user.password
});
} //login
} //myObject
return myObject;
})
这是调用身份验证的地方。在我的注册 Controller 中:
myApp.controller('RegistrationController', function($scope, $firebaseAuth, $location, Authentication) {
$scope.login = function() {
Authentication.login($scope.user)
.then(function(user) {
$location.path('/meetings');
}, function(error) {
$scope.message = error.toString();
});
}//login
$scope.register = function() {
$location.path('/register');
}//register
});//
我什至记录了根作用域以查看 $on() 函数中是否有正确的参数:
$$listeners: Object$firebaseAuth:authWithPassword: Array[1]0: function (e, authUser){length: 1
__proto__: Array[0]
如果有人能提供帮助,我将不胜感激。
最佳答案
Angular Fire 不会在范围内广播事件。您将需要在 promise 完成回调中执行此操作。我建议在您的身份验证服务中这样做。
myApp.factory('Authentication', function ($rootScope, $firebase, $firebaseAuth, FIREBASE_URL, $location) {
var ref = new Firebase(FIREBASE_URL);
console.log(FIREBASE_URL);
var simpleLogin = $firebaseAuth(ref);
var myObject = {
login: function (user) {
return simpleLogin.$authWithPassword({
email: user.email,
password: user.password
}).then(function(authData){
$rootScope.$broadcast('$firebaseAuth:authWithPassword',authData);
return authData;
});
} //login
} //myObject
return myObject;
})
您在处理程序的末尾返回 authData,因此您可以将其他操作链接到同一个 promise (就像您在 RegistrationController 中所做的那样)。
关于javascript - 当我调用它时,angular 的 $rootScope.$on() 方法没有被触发。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27051669/