Whenever I try to invoke the function from another part of the code, I encounter an issue where it returns undefined before actually executing the function. The function is stored in a service.
login.page.ts:
ngOnInit(){
console.log(this.auth.getRole());
}
auth-admin.service.ts:
Initial Approach
getRole() {
this.afAuth.onAuthStateChanged(user => {
if (user) {
this.afs.firestore.doc(`Core/Usuarios/Admin/${user.uid}`)
.get()
.then(userProfileSnapshot => {
let isAdmin = userProfileSnapshot.data().udbid.role;
return isAdmin;
})
}
});
}
CONSOLE LOG
undefined
In my second attempt, I added a console message before returning the value. This time, the desired value showed up in the console eventually, but there was still an initial result of "undefined" before that. Strangely, the function never actually returned the value.
Second Attempt
getRole() {
this.afAuth.onAuthStateChanged(user => {
if (user) {
this.afs.firestore.doc(`Core/Usuarios/Admin/${user.uid}`)
.get()
.then(userProfileSnapshot => {
let isAdmin = userProfileSnapshot.data().udbid.role;
console.log(isAdmin)
return isAdmin;
})
}
});
}
CONSOLE LOG:
undefined
Admin