首页 > 解决方案 > 如何使用 angularfire 查询引用?

问题描述

plans是具有 2 个字段的根集合:daterecipe. recipe是对不同根集合的引用,称为recipes. 我正在尝试构建一个可观察的链,它发出指定日期范围内的计划引用的食谱。

lookup(range: MealPlanRange): Observable<Recipe[]> {
    return this.db.collection('plans', ref=>ref
    .where('date', ">=", range.startDate )
    .where('date', "<=", range.endDate )
    ).valueChanges().pipe(
      // at this point, i have the plans i want, 
      //  but i don't know how to get the recipes
      switchMap(ps=>(/*how to get observable of recipes?*/)),
    );
  }

我试过this.db.doc(p[0].recipe)了,但这并没有返回一个可观察的。我查看了创建一个指定多个 id 的查询,但这似乎是不可能的。有什么建议么?

标签: angularfire2angularfire5

解决方案


找到了:

lookup(range: MealPlanRange): Observable<Meal[]> {
    return this.db.collection('plans', ref => ref
      .where('date', ">=", range.startDate)
      .where('date', "<=", range.endDate)
    ).valueChanges().pipe(
      switchMap(ps => {
        // return empty array when no plans
        if(ps.length === 0) {
           return of([])
        }
        // for each plan, do a doc lookup and use valueChanges() to get observable of changes
        const recipes = ps.map(p => this.db.doc(p.recipe).valueChanges());
        // use combineLatest to get back into an array of recipes, 
        // any change to any recipe will re-emit
        return combineLatest(...recipes);
      }),
    ) as any;
  }

推荐阅读