firebase - Firebase 何时触发 onAuthStateChanged?
问题描述
如果我的 createUserWithEmailAndPassword 函数结构如下
await auth.createUserWithEmailAndPassword(email, password).then((userCredential) => {
code stuff...
return promise
}).then(() => {
...
}).catch(() => {
...
}).finally(() => {
...
})
在承诺链中,onAuthStateChanged 观察者何时会启动?
解决方案
仅当onAuthStateChanged
用户登录或注销时才会触发观察者。
从文档中:
在 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
})
}
推荐阅读
- r - 编织到PDF时如何将代码块保持在Rmd的边距内
- angular - “在 '@angular/core' 中找不到导出 'ɵɵinject'
- vba - 用于与 HIVE 建立 ODBC 连接的 VBA 代码?
- python-3.x - 是否有可能让硒工作得更快?
- powershell - 如果可能不再在网络上,powershell 是否能够从主机名提供 IP 地址?
- python - 控制套接字数据
- php - PHP:向表中插入相同的值时死亡
- html - 与导航栏重叠的内容
- javascript - 在 cytoscapejs 中操作后如何保存图形的整个状态
- scala - 如何返回 TableQuery 的可查询子实例?