I am using an "auth service" to keep all the user authentication functions. When the user is authenticated, I get the user's id and I fetch the relevant record from the database table, but I fail to get the value of the "role" field. The code I am using in the constructor is this:
constructor(
private _firebaseAuth: AngularFireAuth,
private db: AngularFireDatabase,
private router: Router) {
this.user = _firebaseAuth.authState;
this.user.subscribe(
(user) => {
if (user) {
this.userDetails = user;
this.userEmail = this.userDetails.email;
this.uid = this.userDetails.uid;
this.getUserRole(this.uid).subscribe(result => {
this.role = result.role;
console.log('role >>>>>>>>>>>>>', this.role);
});
console.log('uid >>>>>>>>>>>>>', this.uid);
console.log('role >>>>>>>>>>>>>', this.role);
}
else {
this.userDetails = null;
}
}
);
}
getUserRole(userId: string): Observable<any> {
return this.db.list('users', ref => ref.orderByChild('uid').equalTo(this.uid)).valueChanges()
.map(result => result[0]);
}
this.uid
has the correct value, but this.role
is undefined.
I suppose the problem that the call to the database table is asynchronous. How can i get this value?