【问题标题】:Firebase when is onAuthStateChanged triggered?Firebase 何时触发 onAuthStateChanged?
【发布时间】:2021-07-19 16:17:38
【问题描述】:

如果我的 createUserWithEmailAndPassword 函数的结构是这样的

    await auth.createUserWithEmailAndPassword(email, password).then((userCredential) => {
        code stuff...
        return promise
    }).then(() => {
        ...
    }).catch(() => {
        ...
    }).finally(() => {
        ...
    })

onAuthStateChanged 观察者在承诺链中什么时候会启动?

【问题讨论】:

  • 这似乎是您可以通过一些控制台日志自己观察到的。

标签: firebase firebase-authentication


【解决方案1】:

onAuthStateChanged 观察者仅在用户登录或退出时触发。

来自documentation

在 4.0.0 之前,这会在用户登录、退出或用户的 ID 令牌在令牌到期或密码更改等情况下发生更改时触发观察者。 4.0.0之后,观察者只在登录或注销时触发。

要保留旧行为,请参阅firebase.auth.Auth.onIdTokenChanged

也就是说,如果您有 onAuthStateChanged 观察者,它将在用户登录后立即触发,并且您的 .then() 块内的代码可能会或可能不会完全执行。如果您的身份验证观察者在登录后将用户重定向到其他页面,那么您的用户很可能会在您的 then 块完成之前被重定向。

如果你需要在用户登录后执行一些代码,你应该退订auth观察者:

const auth = firebase.auth()

const authObserver = auth.onAuthStateChanged((user) => {
  if (user) {
    // redirect
  }
})


btnLogin.onclick = async function () {
  //unsubscribe
  authObserver()

  await auth.createUserWithEmailAndPassword(email, password).then((userCredential) => {
        // onAuthStateChanged will trigger here if not disabled
        //code stuff...
        //return promise
    }).then(() => {
        // your code
    })
}

【讨论】:

    猜你喜欢
    • 2021-12-06
    • 2022-01-04
    • 2016-10-07
    • 2017-04-10
    • 2020-08-26
    • 2017-12-17
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    相关资源
    最近更新 更多