Handle asynchronous authentication in Firebase on page reload to get list that needs user's uid

女生的网名这么多〃 提交于 2019-12-25 04:20:36

问题


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:

  1. What is the best way to handle this situation.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!