当我第一次创建用户进行身份验证时,如何使用其唯一ID将用户添加到Firebase数据库

时间:2016-11-06 23:54:12

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

这似乎是一个显而易见的问题,但我在Firebase数据库中创建用户时遇到了问题。我对firebase和编码很新。

我理解的是,当用户点击注册按钮时,将在“object / users”下创建具有新认证的uid的用户。但是用户始终为null。在google documentation中它说有时用户是null因为它还没有完成初始化用户。并把它放在onAuthStateChanged里面。但是,如果我这样做,每次登录时都会创建/覆盖用户在或退出。

我想我正在寻找的是在用户首次注册有效信息时在我的firebase数据库中创建用户的一些解决方案。

这是我的代码:

  function LoginCtrl($scope) {
    $scope.txtEmail = document.getElementById('txtEmail');
    $scope.txtPassword = document.getElementById('txtPassword');
    $scope.btnLogin = document.getElementById('btnLogin');
    $scope.btnSignUp = document.getElementById('btnSignUp');
    $scope.btnLogout = document.getElementById('btnLogout');


    btnLogin.addEventListener('click', e => {
        const email = txtEmail.value;
        const pass = txtPassword.value;
        const auth = firebase.auth();

        const promise = auth.signInWithEmailAndPassword(email, pass);
        promise.catch(e => console.log(e.message));

    });

    btnSignUp.addEventListener('click', e => {
        const email = txtEmail.value;
        const pass = txtPassword.value;
        const auth = firebase.auth();
        const promise = auth.createUserWithEmailAndPassword(email, pass);
        promise.catch(e => console.log(e.message));

        createUser();
    });

    function createUser() {
        var user = firebase.auth().currentUser;

        if (user != null) {
            const dbRefObject = firebase.database().ref().child('object');
            const dbRefList = dbRefObject.child("users/" + user.uid);
            dbRefList.set({
                name: "jim",
            });
        } 
    }

    btnLogout.addEventListener('click', e => {
        firebase.auth().signOut();
    });

    firebase.auth().onAuthStateChanged(firebaseUser => {
        if (firebaseUser) {
            console.log(firebaseUser);
            btnLogout.classList.remove('hide');
            btnLogin.classList.add('hide');
        } else {
            console.log('not logged in');
            btnLogout.classList.add('hide');
            btnLogin.classList.remove('hide');
        }
    })
}

1 个答案:

答案 0 :(得分:1)

罪魁祸首是这三行:

const promise = auth.createUserWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
createUser();

你过早地开除了createUser()。在上面的代码片段中,这恰好在启动(异步)注册过程后发生 - SDK从未有机会在auth数据库中实际创建用户!

createUserWithEmailAndPassword返回一个承诺,反映在您的本地变量中。你需要做的是链接两个调用,即在完成承诺后启动数据库操作

试试这个:

// inside the click handler
btnSignUp.addEventListener('click', e => {
    const email = txtEmail.value;
    const pass = txtPassword.value;
    const auth = firebase.auth();

    auth.createUserWithEmailAndPassword(email, pass)
        .then(user => createUser(user)) // <-- important!
        .catch(e => console.log(e.message));
});

function createUser(user) {
    // no need for currentUser if you pass it in as an argument
    if (user) {
        ...
    }
}