I'm trying to use Firebase v9 modular version and I'm confused as to how to use onSnapshot. I'm trying to execute a query and listen to the documents.
Following is my code :
getUsersBoards(){
return this.authService.currentUser$.pipe(
filter((user)=> !!user),
mergeMap(async (user) => {
const collectionRef = collection(this.firestore, 'boards');
const q = query(collectionRef, where("owner", "==", user.uid));
return onSnapshot(q, (querySnapshot)=>{
return querySnapshot;
});
})
);
}
I was expecting an Observable<board[]>
, but I'm getting a Observable<unsubscribe>
Is there a way so that I can do the following ?
boards$: Observable<board[]>;
...
this.boards$ = getUsersBoards();
You're getting Observable<unsubscribe>
because, according to the Firebase docs, onSnapshot
returns "[a]n unsubscribe function that can be called to cancel the snapshot listener."
Try converting the snapshot to an observable first, before returning. For example:
new Observable(observer => {
return onSnapshot(reference,
(snapshot => observer.next(snapshot.data())),
(error => observer.error(error.message))
);
});