保存用户关于注册firebase的额外详细信息

时间:2016-06-29 13:48:25

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

我想保存用户的额外详细信息,即数字,仅在用户注册时使用年龄(一次)。但是没有回调来检查注册是否成功。

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

所以当你想在用户注册而不是使用

时只存储一次数据时该怎么办
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

每次用户登录/注销时都会触发,但我不想每次都保存额外的注册详细信息。

2 个答案:

答案 0 :(得分:6)

firebase.auth().createUserWithEmailAndPassword($scope.email, $scope.password)
        .then(function(user) {
            var ref = firebase.database().ref().child("user");
            var data = {
                email: $scope.email,
                password: $scope.password,
                firstName: $scope.firstName,
                lastName: $scope.lastName,
                id:user.uid
            }
            ref.child(user.uid).set(data).then(function(ref) {//use 'child' and 'set' combination to save data in your own generated key
                console.log("Saved");
                $location.path('/profile');
            }, function(error) {
                console.log(error); 
            });
        })
        .catch(function(error) {
            var errorCode = error.code;
            var errorMessage = error.message;
            if (errorCode == 'auth/weak-password') {
                alert('The password is too weak.');
            } else if (errorCode == 'auth/email-already-in-use') {
                alert('The email is already taken.');
            } else if (errorCode == 'auth/weak-password') {
                alert('Password is weak');
            } else {
                alert(errorMessage);
            }
            console.log(error);
        });

result 在这里,我将数据保存在'user.uid'键中,该键在成功注册用户后由firebase返回。

答案 1 :(得分:2)

致电createUserWithEmailAndPassword()会返回一个承诺,该承诺同时包含catch()then()方法。

Firebase文档故意不使用then()子句,因为它通常更好地响应onAuthStateChanged()事件(当用户重新加载应用时也会触发)即使在您的情况下,可能是将代码存储在用户配置文件中的更好位置,因为某些数据可能会在应用重新加载时发生变化。

但是如果您想明确回复"用户已成功创建",您可以这样做:

firebase.auth()
    .createUserWithEmailAndPassword(email, password)
    .then(function(user) {
        console.log("Create user and sign in Success", user);
    });
相关问题