【问题标题】:Firebase web app - can't get user.uid when creating new accountFirebase Web 应用程序 - 创建新帐户时无法获取 user.uid
【发布时间】:2018-07-09 15:21:25
【问题描述】:

我正在开发一个小型网络应用程序,但遇到了似乎无法克服的障碍。我可以注册一个新帐户,但我想在注册后立即将其他数据保存到数据库中。

这就是我所拥有的,我相信它可以正常工作。

$("#user-sign-up-button").click(function(){


  var firstName = $("#new-user-first-name").val();
  var secondName = $("#new-user-surname").val();
  var charity = $("#new-user-charity-account").val();
  var userEmail = $("#new-user-email").val();
  var userPassword = $("#new-user-password").val();
  var secondPassword = $("#new-user-repeated").val();

  firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword)
  
  .catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    // ...
  });


});

现在关于将其他变量保存到数据库中,我在 createuserWithEmailAndPassword 的 .then 部分中尝试了以下两种方法。

.then(
    function(user){
      var root = firebase.database().ref();
      var uid = user.uid;
      alert(uid);
      var postData = {  firstName: first_name,
        secondName: second_name,
        email: user_email,
        isCharity: charity };
        root.child("users").child(uid).set(postData);
    }

    function writeUserData(first_name, second_name, charity, user_email) {
      firebase.database().ref('users/' + user.uid).set({
        firstName: first_name,
        secondName: second_name,
        email: user_email,
        isCharity: charity
    });
  )

上述两种解决方案都可以在 onAuthStateChanged 中工作,但我想在注册时捕获数据,而不是每次有人登录时。

任何帮助都会很棒。

【问题讨论】:

  • “我在 createuserWithEmailAndPassword 的 .then 部分中尝试了以下两种方法。” 是我还是您没有在问题中添加那部分代码?我只看到 catch 错误...

标签: javascript jquery firebase firebase-realtime-database


【解决方案1】:

您必须使用.onAuthStateChanged 才能访问firebase.auth().currentUser。它是异步的,在解决之前将为空/null。另外,不要忘记新的基于电子邮件的帐户在单击验证电子邮件链接之前不会是.emailValidated:true。 ...需要考虑的事情。

【讨论】:

  • 如果我确实使用 onAuthStateChanged,是否会在每次有人登录时重新提交信息,并检查是否将此数据添加到数据库中?因为这似乎太过分了,而且放在那里有点不对劲哈哈。
  • "对于 Web 应用程序,默认行为是保留用户会话,即使在用户关闭浏览器后也是如此。" source
猜你喜欢
  • 2021-10-04
  • 2020-03-20
  • 1970-01-01
  • 2017-11-07
  • 2021-08-01
  • 1970-01-01
  • 2019-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多