linking created users to database in firebase web app

♀尐吖头ヾ 提交于 2019-12-13 07:29:53

问题


How do I link the authenticated users to my firebase database in my Angular JS web app?

I understand that I would have to create a node in my database tree for each user. I have created a node in my database tree called "users" for this. What I do not understand is how to get each user to occupy a sub-node in my "users" node in my database such that once logged in, all the data each user saves is saved under their respective sub-nodes.

This is my code at the moment:

         $scope.saveTeam = function(user){
$scope.history = [];

 var uid = user.uid;

var ref2 = firebase.database().ref("users/" + uid + "/week"); 


 ref2.set($scope.history);

  };

回答1:


Which ever method you are using to signup users has a promise returned .

For example consider signing up users with email and password:

firebase.auth().createUserWithEmailAndPassword(username, password).then(
    (user) =>{
        let usersRef = firebase.database().ref("users");
         //child is created under users node with a user's user id as child name
        usersRef.child(user.uid).set({
            email: user.email,
            userName: username,
            displayPicUrl: 'any url.'
          });
    }, error => {
        //handle errors here
    }
); 

So you can do the process of writing a new user to database in ths promise's fullfilled part as shown above. This ensures that a user node is created only if user sign up was successful

so in your code add like this

$scope.signUp = function (){
   var username = $scope.user.email;
   var password = $scope.user.password;
   if(username && password){
         var auth = $firebaseAuth();
             auth.$createUserWithEmailAndPassword(username, password).then(function(user){
                 console.log("User Successfully Created");
                let usersRef = firebase.database().ref("users");
                 //child is created under users node with a user's user id as child name
                usersRef.child(user.uid).set({
                    email: user.email,
                    userName: username,
                    displayPicUrl: 'any url.'
                  });

                 $location.path('/home');
             }).catch(function(error){
                $scope.errMsg = true;
                $scope.errorMessage = error.message;
             });
 }
 }; 

You are not passing user parameter in then()



来源:https://stackoverflow.com/questions/43951888/linking-created-users-to-database-in-firebase-web-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!