问题
Using Angularjs. How do you handle the situation where a person reloads a page and the controller tries to query Firebase using the current user's uid before the Firebase auth event is triggered and has a chance to set the current user?
Details: The Firebase query require's the user's uid and everything works when navigated to the route via $state.go('/list')
But when a person reloads the page the controller checks for the user which doesn't exist until this event handler fires:
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
})
If Firebase still had the synchronous auth call this wouldn't be an issue since I could do the check and call at the beginning of the controller.
So:
- What is the best way to handle this situation.
- If user is not logged in, how does UserSrvc.getUser() navigate to $state.go('/login') without having Posts.list() execute?
回答1:
The common way to implement this is by moving the loading of the posts into 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');
}
})});
});
You'll note I added a $timeout()
in there, since otherwise Angular won't be aware of the update we've made to $scope
.
Note that we have a dedicated library binding Firebase to AngularJS called AngularFire, which does a lot of this automatically for you.
来源:https://stackoverflow.com/questions/39534822/handle-asynchronous-authentication-in-firebase-on-page-reload-to-get-list-that-n