Reputation: 87
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?
Upvotes: 1
Views: 602
Reputation: 8002
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
}
}))
Upvotes: 1