为了账号安全,请及时绑定邮箱和手机立即绑定

将回调附加到onauthStateChanged侦听器firebase

将回调附加到onauthStateChanged侦听器firebase

冉冉说 2021-04-06 17:14:34
我有此代码,我只需要返回一个uid,以便以后可以使用Id进行Firestore操作$(document).ready(function () {    var uid;    auth.onAuthStateChanged(function (user) {        if (user != null) {            uid = user.uid;             console.log(typeof uid)//returns a string ;        }    });    console.log(uid);    function fetch() {        var docRef = db.collection("Users").doc(uid);        docRef.get().then(function (doc) {            console.log(doc.data);        }).catch(function (error) {            console.log("Error getting document:", error);        });    }});我如何存储uid以便以后检索它以进行数据库操作。当前,运行该check函数将返回uid未定义的错误。如果我尝试登录uid控制台也一样。我猜该函数在侦听器解析之前运行,但是我将如何解决此问题。由于用户之间的互联网连接速度不同,设置计时器也无济于事(添加代码)check1();check3();//fetch();function check1() {    if (typeof uid === 'undefined') {        console.log("not ready");        return false    }}function check3() {    if (check1 == false) {        check1();    } else {        console.log("ready");  //here this logs ready        console.log(typeof uid); //then here it logs "undefined" still        fetch(); //so this function call brings the error    }}function fetch() {    var docRef = db.collection("Users").doc(uid);    docRef.get().then(function (doc) {        console.log(doc.data();    }).catch(function (error) {        console.log("Error getting document:", error);    });}check3如果uid未定义,为什么函数准备好记录日志。我还需要隐藏特定的链接,直到uid具有值为止。我该如何改善上述代码而无法隐藏链接
查看完整描述

1 回答

?
繁华开满天机

TA贡献1816条经验 获得超4个赞

check在身份验证成功完成之前,您的猜测几乎可以肯定是正确的。设置计时器并不能真正帮助您防弹。

由于我们不知道您需要何时或在什么条件下致电check,因此建议采取不同的措施是很困难的。至少,check应该检查uid是否尚未定义,如果不存在,请拒绝执行任何操作。

通常,UI将被编码为在用户成功登录之前不允许用户执行任何操作。


查看完整回答
反对 回复 2021-04-08
  • 1 回答
  • 0 关注
  • 152 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号