【问题标题】:Javascript and Firebase - Create user with Email and password and onAuthStateChangeJavascript 和 Firebase - 使用电子邮件和密码以及 onAuthStateChange 创建用户
【发布时间】:2018-08-10 06:02:24
【问题描述】:

您好,我在寻找一种方法将身份验证状态更改自动定向到已登录用户的页面时遇到问题。但是,在创建用户之前,我想将用户配置文件推送到我的数据库。

所以我创建了用户,然后用这段代码添加到数据库中

firebase.auth().createUserWithEmailAndPassword(email, password).then(function (user){
  firebase.database().ref('/Profiles').child(user.uid).set({
    address: ''
  })
}).catch(function(error){
  let errorCode = error.code;
  let errorMessage = error.message;
  navigator.notification.alert('Error: Code: ' + errorCode + ', ' + errorMessage,false,'Error','Done');
});

但是,一旦 createUserWithEmailAndPassword 成功,此 onAuthStateChanged 函数会在添加数据库“配置文件”记录之前导航到新页面。

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    let u = firebase.auth().currentUser;
    window.location = 'loggedIn.html';

  }
});

如何让我的 onAuthStateChanged 函数在离开页面之前等待添加数据库记录

注意:: 我想保留 onAuthStateChanged,这样如果用户登录到会话,他们将自动定向到登录页面

【问题讨论】:

    标签: javascript firebase firebase-authentication


    【解决方案1】:

    我遇到了同样的问题。我尝试了几种方法,但一个简单的 setState 出于某种原因解决了这个问题。

    尝试为 createUserWithEmailAndPassword 函数中的某些内容设置状态。例如:

    firebase.auth().createUserWithEmailAndPassword(email, password).then(function (user){
      firebase.database().ref('/Profiles').child(user.uid).set({
        address: ''
      })
      // SET Some state
      this.setState({ error: null, isLoading: false });
    
      // Besides that I show the feedback as an alert (just in case you think it's a good idea)
      Alert.alert(
          `Welcome ${user.user.name}!`,
          'Your account has been successfully created.',
          [
            {
              text: 'OK',
              onPress: () =>
                navigation.navigate('Main'),
            },
          ]
        );
    
    }).catch(function(error){
      let errorCode = error.code;
      let errorMessage = error.message;
      navigator.notification.alert('Error: Code: ' + errorCode + ', ' + errorMessage,false,'Error','Done');
    });
    

    【讨论】:

      【解决方案2】:

      您可以在保存到数据库后尝试注册 onAuthStateChagned 处理程序。

      【讨论】:

        猜你喜欢
        • 2016-11-27
        • 2018-03-12
        • 2020-10-08
        • 2019-07-10
        • 2017-11-25
        • 2018-10-06
        • 2018-03-25
        • 2017-08-26
        • 2016-06-27
        相关资源
        最近更新 更多