Firebase检索用户信息

时间:2017-09-18 19:26:04

标签: javascript firebase web firebase-realtime-database firebase-authentication

我正在尝试检索已登录的用户ID,以便使用firebase从数据库中检索与他相关的信息....

在我的HTML页面内的标签我有以下内容 -

    var user
    var uid;
    firebase.auth().onAuthStateChanged(user => {
        if(!user) {
            window.location = 'login.html'; //If User is not logged in, redirect to login page
        } else {
            user = firebase.auth().currentUser;
            uid = user.uid;
        }
    });

    console.log("UID: " + uid);

并且,它似乎正在检查用户是否登录...因为如果我从主页面登录并转到该页面,它就可以运行并转到页面,但如果我当我没有登录时转到该页面,它会重定向到登录页面...

然而,当我尝试执行该日志语句时,它打印出未定义的uid ...任何想法为什么这不起作用?

1 个答案:

答案 0 :(得分:0)

firebase promise需要一些时间来处理onAuhtStateChanged中的业务逻辑,所以你的consoles.log将首先被调用并在调用onAuhtStateChanged promise之前将UID打印为undefined,尝试编写如下代码

  var user
  var uid;
firebase.auth().onAuthStateChanged(user => {
    if(!user) {
        window.location = 'login.html'; //If User is not logged in, redirect to login page
    } else {
        user = firebase.auth().currentUser;
        uid = user.uid;
        _callPrintUserUID(uid)
    }
});

var _callPrintUserUID=function(uId){
   console.log("UID: " + uid);//print your global variable.
   console.log("UID: " + uId)// parameter passed.
}

我希望这可以帮助您随意对此答案提出任何疑问。 See this answer, i have already answered the more similar question to yours