I am trying to fetch a list of users from my firestore database, and determine if the logged in user is an admin (i.e. he's in the list).
This is my code:
isAdmin(user: any): boolean {
var col = this.afs.collection('admins');
var docRef = col.doc('mini-admins');
docRef.ref.get().then(function (doc) {
if (doc.data().user == user)
return true;
}).catch(function (error) {
console.log("Error getting document:", error);
});
return false;
}
However, even though the user is an admin, the function doesn't work. It looks like it isn't waiting for it to finish before proceeding.
How do I fix this?
angular2 wait until observable finishes in if condition. this if condition waits for a response from the backend. But before the observable gets executed it's going into the else statement and finishing the condition without checking the if condition at start.
this if condition waits for a response from the backend. But before the observable gets executed it's going into the else statement and finishing the condition without checking the if condition at start. Show activity on this post. You can't wait for an Observable or Promise to complete.
Coming from the pre-Angular2 Angular.js world, Angular (which is already at version 5 at the time of writing) can seem daunting with its insistence of using the Observer/Observable design pattern. Everywhere you look, things seem to return an RxJS Observable instead of that nice familiar promise we all know (and maybe even love?).
Use of async or await () function: This method can be used if the exact time required in setTimeout () cannot be specified. The async keyword is used to create an asynchronous function that returns a promise that is either rejected or resolved.
It's not working because it's asynchronous. To make it work you need to change it slightly to:
isAdmin(user: any): Observable<boolean> {
return new Observable(observer => {
var col = this.afs.collection('admins');
var docRef = col.doc('mini-admins');
docRef.ref.get().then(function (doc) {
if (doc.data().user == user) {
observer.next(true);
observer.complete();
}
}).catch(function (error) {
observer.error(error);
observer.complete();
console.log("Error getting document:", error);
});
});
}
Then in your code when you want to check if the user is admin, call this function in the following way:
this.isAdmin(user).subscribe(success => { ... }, error => { ... });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With