[英]Handle asynchronous authentication in Firebase on page reload to get list that needs user's uid
使用Angularjs。 在触发Firebase身份验证事件并有机会设置当前用户之前,您如何处理某人重新加载页面且控制器尝试使用当前用户的uid查询Firebase的情况?
详细信息:Firebase查询需要用户的uid,并且通过$ state.go('/ list')导航到路由时,一切正常
但是,当有人重新加载页面时,控制器会检查该用户是否存在,直到触发此事件处理程序为止:
auth.onAuthStateChanged(function(user) {
if (user) {
//Set user
UserSrvc.currentUser = user;
} else {
$state.go('/login');
}
});
app.controller('ListCtrl', function($scope, UserSrvc, Posts ) {
if (!UserSrvc.currentUser){
UserSrvc.getUser();
};
$scope.posts = Posts.list(); <--THIS GENERATES ERROR, SINCE NO USER YET
})
如果Firebase仍然具有同步auth调用,这将不是问题,因为我可以在控制器的开头进行检查和调用。
所以:
实现此目的的常用方法是将帖子的加载移动到onAuthStateChanged()
:
app.controller('ListCtrl', function($scope, UserSrvc, Posts ) {
auth.onAuthStateChanged(function(user) { $timeout(function() {
if (user) {
UserSrvc.currentUser = user;
if (!UserSrvc.currentUser){
UserSrvc.getUser();
};
$scope.posts = Posts.list();
} else {
$state.go('/login');
}
})});
});
您会注意到我在其中添加了$timeout()
,因为否则Angular不会知道我们对$scope
所做的更新。
请注意,我们有一个专用的库将Firebase绑定到AngularFire ,将其绑定到AngularJS ,它会自动为您执行很多操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.