如何等待FirebaseAuth完成初始化?

时间:2016-08-30 15:17:46

标签: android firebase firebase-authentication

对我的应用进行集成Firebase身份验证。一切似乎都很好,直到我注意到我打开应用程序的问题,它向我显示登录屏幕,即使已经有用户登录。

退出应用并再次启动它可以解决问题(应用不再要求用户再次登录),但它会为用户提供非常糟糕的体验。

我已经阅读了文档,显然,如果auth尚未完成初始化,则调用FirebaseAuth.getInstance().getCurrentUser()可能会返回null。我假设这就是问题发生的原因。所以我想知道在调用getCurrentUser()之前是否有办法等待FirebaseAuth完成初始化?

6 个答案:

答案 0 :(得分:3)

您可以创建返回promise的函数,并在需要的地方等待:

window.location.origin

选中此项-https://github.com/firebase/firebase-js-sdk/issues/462

答案 1 :(得分:1)

使用现代API,只需等待auth状态更改即可:

firebase.auth().onAuthStateChanged(user => init_your_app);

答案 2 :(得分:1)

无法相信我必须这样做(因为Google没有官方API)。我必须再使用一个布尔值...

let isAuthReady = false

firebase.auth().onAuthStateChanged((user) => {
  store.commit('setUser', user)

  if (!isAuthReady) {
    isAuthReady = true
    init()
  }
})

答案 3 :(得分:1)

对于问相同问题的React用户:

react-firebase-hooks有一个名为useAuthState的钩子,可以证明对检查Firebase身份验证的状态很有帮助。 我认为以下是一个非常常见的用例。

import {useAuthState} from "react-firebase-hooks/auth";
import React from "react";

export default function AllowIfAuth() {
    const [user, loading, error] = useAuthState(auth);
    if (loading) {
        return <div> Loading... </div>;
    } else if (user) {
        return <div> Some Content </div>;
    } else if (error) {
        return <div>There was an authentication error.</div>;
    } else {
        return <LoginPage/>;
    }
}


答案 4 :(得分:0)

您需要一个监听器,告诉您身份验证何时完成,此链接可能会对您有所帮助:FirebaseAuth.AuthStateListener

答案 5 :(得分:0)

您可以致电getCurrentUser()来了解,如果在此时刻,已知用户已登录。如果您需要在用户登录或注销时触发一些代码,你需要注册一个监听器,以便在发生变化时得到通知。有一个方法addAuthStateListener()将触发该更改。请务必阅读该javadoc以准确了解它将触发的条件。在您添加的AuthStateListener旁边,您可以调用getCurrentUser()来了解用户是否已登录。

相关问题