My goal is to retrieve user details from my firebase database while using Ionic and Typescript.
Here is how I add a user:
addToDatabase(user: User) {
let isInstructor = user.isInstructor == null ? false : user.isInstructor;
this.afDB.list("/users/").push(
{
"firstName": user.firstName,
"lastName": user.lastName,
"email": user.email,
"institution" : user.institution,
"isInstructor": isInstructor
}
);
}
The user is successfully created
Next, I access the data in this manner:
async signIn(user: User) {
this.afAuth.auth.signInWithEmailAndPassword(user.email, user.password).then((result) => {
var ref = this.afDB.database.ref("users/");
//retrieve values for a single user by email
ref.orderByChild("email").equalTo(user.email).once("value").then(function (snapshot) {
console.log(snapshot.val());
var value = snapshot.val();
console.log(value);
var firstName = value.firstName;
console.log(value.firstName);
var lastName = JSON.stringify(value.lastName);
console.log(lastName);
//user.firstName = value.firstName; Save user details here
//user.lastName = value.lastName; and here for later
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
this.shareService.setUserDetails(user); //User detail is shared in the app
this.navCtrl.setRoot(HomePage);
}).catch(function (error) {
alert("Sign in failed:\n" + error.message);
});
}
This part appears to be functioning correctly as I can view the user object in Chrome.
However, when attempting to display the object on the page's HTML, it often shows up as "undefined."
var value = snapshot.val();
console.log(value); //Displays the object as expected
console.log(value.firstName); //Desired property but returns "undefined"
var lastName = JSON.stringify(value.lastName); //Attempt to stringify
console.log(lastName); //Still "undefined"
I've explored various solutions not included in the provided code. Yet, I am unable to obtain the desired data.
Update: I've added the JSON export of my database for reference:
{
"users" : {
"-L6JNUj7T9wvssjiWjX9" : {
"email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e195849295a195849295cf828e8c">[email protected]</a>",
"firstName" : "testFirst",
"institution" : "school-university",
"isInstructor" : false,
"lastName" : "testLast"
}
}
}
Update: Attempting to use promises also results in returning null.
public dataTest(user: User) {
var ref = this.afDB.database.ref("users/");
return new Promise(function (resolve, reject) {
try {
ref.once('value', function (snapshot) {
if (typeof snapshot.val().firstName === 'undefined') {
resolve(null);
} else {
console.log(snapshot.val().firstName);
resolve(snapshot.val().firstName);
}
})
} catch (e) {
reject(e)
}
});
}
this.dataTest(user).then(function (result) {
console.log("result " + result) //Returns null
}).catch(function (error) {
console.log(error)
})