【问题标题】:Have I called the onAuthStateChanged function incorrectly?我是否错误地调用了 onAuthStateChanged 函数?
【发布时间】:2017-09-13 05:39:29
【问题描述】:
githubLogin.addEventListener('click', () => {
    var provider = new firebase.auth.GithubAuthProvider();

    firebase.auth().signInWithPopup(provider).then(function(result) {
        var user = result.user;
        console.log(user);
        firebase.auth().onAuthStateChanged(function(user) {
            if (user) {
                window.location = "pages/welcome.html";
            }});
    }).catch(function(error) {
        console.log(error);
    });

});

所以问题是,当我将用户重定向到 Welcome 时,我看到该页面上没有用户登录。 我知道我必须使用 onAuthStateChanged() 函数,但到目前为止我错了。我可以知道如何做到这一点吗?而且我也有类似的谷歌登录,这会影响功能吗?

【问题讨论】:

    标签: javascript firebase firebase-authentication


    【解决方案1】:

    您应该在显示按钮之前确定身份验证状态。如果onAuthStateChanged 侦听器最初以空用户触发,则显示登录屏幕。

    另外,当您调用signInWithPopup 时,您不需要添加状态更改监听器。你可以这样做:

    firebase.auth().signInWithPopup(provider).then(function(result) {
      // User logged in, you can get currentUser from onAuthStateChanged
      // listener on welcome page.
      window.location.assign("pages/welcome.html");
    }).catch(function(error) {
      // Handle error.
    });
    

    【讨论】:

    • 我做过这样的事情.....但它似乎不再起作用了..codepen.io/kol730/pen/QqWBZz
    • 请提供详细信息。
    • 我刚刚添加了上面的链接
    • 您在滥用onAuthStateChanged 监听器。您是否在欢迎页面上添加了该侦听器?您只显示您的登录代码,而不是登录用户登陆的代码。还要描述你正在经历的事情。重定向到欢迎页面是否有效?如果是这样,用户应该已登录,但您在欢迎页面上没有检测到它。
    • 当用户被重定向到欢迎页面时,我已经这样做了。 const fireUser = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function (user){ fireUser = user; document.getElementById('welcome-message').innerHTML = firebase.auth().currentUser.displayName; })
    猜你喜欢
    • 2015-05-08
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多