繁体   English   中英

使用 FireStore 查询集合和过滤文档并返回 Observable

[英]Querying a collection and filtering documents using FireStore and returning Observable

这里是火库

云防火墙

目前在下面的代码中,我可以通过 Id 查询集合,这是每个单独配方的 Id。 这有自己的目的,现在我想查询配方集合的文档,它只返回属于登录用户的食谱。 它还应该返回 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[]>;
 }

这是我得到的错误,它无法转换为 Observable:

将 'Promise<QuerySnapshot>' 类型转换为 'Observable<Recipe[]>' 类型可能是一个错误,因为这两种类型都没有充分重叠。 如果这是故意的,请先将表达式转换为“未知”。

我可以在 Observable 客户端进行过滤,但我认为在这种情况下使用查询过滤数据是更好的设计实践。 谁能指出我正确的方向?

getDocs返回 promise。

您可以使用from(getDocs(q))转换为 observable。
不过,您可能必须先投射

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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