Reputation: 225
I have some data in firebase ( email id and password being the keys). I'm passing an email id, and want to retrieve the corresponding password to check for validation. But, when I try to print the retrieved value on console, it prints "null" even though the data exists in firebase.
getPassword(email:string)
{
console.log(email);
this.db.database.ref('/facility').orderByChild('email').equalTo(email).once('value', (snapshot) => {
//console.log(snapshot.val());
if(snapshot.val())
{ this.userpassword = snapshot.val().password;
return this.userpassword;}
})
}
I have tried passing email as [email protected] expecting to recieve "akhilesh" from the database but received null.
verifyuser(email: string){
this.userService.getPassword(email);
}
Upvotes: 0
Views: 1554
Reputation: 83191
This is because, through snapshot.val()
, you receive the "full" object, i.e.
{ Akhilesh : {
email: .....,
password: .....
}
}
as you may have seen with console.log(snapshot.val());
. As a matter of fact, you call the once()
method on database.ref('/facility')
.
The following will therefore do the trick:
var dataObj = snapshot.val();
var password = dataObj[Object.keys(dataObj)[0]].password;
Note that this solution will work if you are sure that there is only one node corresponding to the email.
If it is not the case you will need to loop over the snapshot, as follows:
this.db.database.ref('/facility').orderByChild('email').equalTo(email).once('value', snapshot => {
snapshot.forEach(childSnapshot => {
var childData = childSnapshot.val();
var password = childData.password;
});
});
You have to wait that the Promises returned by the once()
method resolves, with then()
, as follows:
return this.db.database.ref('/facility').orderByChild('email').equalTo(email)
.once('value')
.then(dataSnapshot => {
if(snapshot.val()) {
var dataObj = snapshot.val();
var password = dataObj[Object.keys(dataObj)[0]].password;
return password;
}
});
Upvotes: 2