使用firebase重定向后保留用户

时间:2017-08-05 15:29:11

标签: javascript firebase firebase-authentication

我目前在Web上使用firebase进行侧面项目,它使用用户身份验证。我让用户登录,然后创建一个游戏室,重定向到游戏的单独页面" room"。页面重定向后虽然我无法提取任何用户数据,但我这样做的唯一方法是重新初始化firebase并使用

auth.onAuthStateChanged(function(user) {
  if (user && user != null) {
    uid = user.uid;
    email = user.email;
    currUser = user;
  } else {
    //user isnt logged in
    window.location.href = 'index.html';
  }

似乎可能有一种更简单的方法来做到这一点,但我似乎无法让它工作,这种方式也会混淆我的其他代码的部分。

1 个答案:

答案 0 :(得分:3)

附加onAuthStateChanged回调是获取用户的惯用方法。

也可以通过firebase.auth().currentUser获得用户。但是,如果需要令牌刷新,则在这种情况下您可能会错误地检测到没有用户。这就是推荐onAuthStateChanged回调的原因。

请参阅Firebase documentation on getting the current user

相关问题