简体   繁体   中英

Querying a collection and filtering documents using FireStore and returning Observable

Here is the Firestore

云防火墙

Currently in the code below I can query the collection by Id which is the Id for each individual recipe. This serves its own purpose and now now I want to query the documents of the recipe collection which only returns recipes which belong to the signed in user. It should also return Observable<Recipe[]>.

//firebase imports:
import {
  DocumentData,
  addDoc,
  collection,
  where,
  query,
  deleteDoc,
  doc,
  updateDoc,
} from '@firebase/firestore';
import { initializeApp } from 'firebase/app';

import { Firestore, docData, getDocs } from 
'@angular/fire/firestore';

constructor(private fireStore: Firestore, private auth: AuthService) {}

@Injectable({
  providedIn: 'root',
})

export class RecipeService {

  recipeCollection = collection(this.fireStore, 'recipes');

 getRecipeById(id: string): Observable<Recipe> {
  const recipeDocumentReference = doc(this.recipeCollection, id);
  return docData(recipeDocumentReference, {
    idField: 'id',
  }) as Observable<Recipe>;
}  

getAllRecipesByUserId(): Observable<Recipe[]> {
 const q = query(this.recipeCollection, where("userId", "==", 
 this.auth.getCurrentUser()));
 return getDocs(q) as Observable<Recipe[]>;
 }

This is the error I am getting so clearly it can't cast to an Observable:

Conversion of type 'Promise<QuerySnapshot>' to type 'Observable<Recipe[]>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

I can do the filter on the Observable client side but I think its better design practice to use a query to filter data in this case. Can anyone point me into the right direction?

getDocs return a promise.

You can use from(getDocs(q)) to convert to observable.
You may have to cast first though

    return from(getDocs(q).then(qs => {
      // map to recipe data
      return qs.docs.map(doc => {
        return { ...doc.data() } as Recipe
      }
    }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM