问题
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