RXJS AngularFire - 从 Observable 获取可观察量



我一直在尝试从Firebase获取数据(使用Angular(。

计划摘要

这是一个小应用程序,用于存储膳食食谱,其成分以根据膳食计划生成累积的购物清单 - 每天,每周等。

我有什么:

1. Firebase数据库结构(其片段(

Ingredients (collection)
Id: string
Name: string
Tags: array of string
Recipes (collection)
CreatedOn: Timestamp
MealTitle: string
MealType: string
Method: string
RecipeIngredients (subcollection)
Id: string
IngredientId: string
ExtendedDescription: string
QTY: number
UOM: string

如您所见,食谱集合包含食谱成分子集合,其中包含来自成分集合的成分 ID和一些其他数据。

2. 从食谱中获取特定配方的成分子集合的成分列表的方法

getRecipeIngredients(recipeId: string): Observable<RecipeIngredient[]> {
this.recipesCollection = this.afs.collection('Recipes', ref => ref.orderBy('CreatedOn', 'desc'));
this.recipeIngredients = this.recipesCollection.doc(recipeId).collection('RecipeIngredients').snapshotChanges().pipe(
map(changes => {
return changes.map(action => {
const data = action.payload.doc.data() as RecipeIngredient;
data.Id = action.payload.doc.id;
return data;
})
})
)
return this.recipeIngredients;
}

3. 根据其ID获取特定成分的方法

getIngredientById(ingredientId: string): Observable<Ingredient> {
this.ingredientDoc = this.afs.doc<Ingredient>(`Ingredients/${ingredientId}`);
this.ingredient = this.ingredientDoc.snapshotChanges().pipe(
map(action => {
if (action.payload.exists === false) {
return null;
} else {
const data = action.payload.data() as Ingredient;
data.Id = action.payload.id;
return data;
}
})
)
return this.ingredient;
}

4. 我想要实现的目标

我想在包含以下列的表格中显示特定配方的成分列表:成分名称、扩展描述、数量、UOM。问题是我不知道如何获得成分名称。 对我来说,合理的解决方案是在getRecipeIngredients中执行此操作,并通过该字段或整个成分集合扩展其返回结果。我尝试了像mergeFlat或combineLate这样的RxJS运算符,但我卡住了。

我当然可以改变数据库结构,但这对我来说也是一个学习项目。我相信我迟早会遇到这样的挑战。

这是一个有趣的问题,但我想我已经解决了。请查看我的StackBlitz。这个决策树通常足以为你提供大多数可观察场景的函数,但我相信这个决策树需要函数的组合。

相关代码:

const recipeId = 'recipe1';
this.recipe$ = this.getRecipeIngredients(recipeId).pipe(concatMap(recipe => {
console.log('recipe: ', recipe);
const ingredients$ = recipe.recipeIngredients.map(recipeIngredient => this.getIngredientById(recipeIngredient.id));
return forkJoin(ingredients$)
.pipe(map((fullIngredients: any[]) => {
console.log('fullIngredients: ', fullIngredients);
fullIngredients.forEach(fullIngredient => {
recipe.recipeIngredients.forEach(recipeIngredient => {
if (recipeIngredient.id === fullIngredient.id) {
recipeIngredient.name = fullIngredient.name;
}
});
});
return recipe;
}));
})).pipe(tap(finalResult => console.log('finalResult: ', finalResult)));

我包括控制台日志,以帮助说明数据在管道传输时的状态。这里的主要思想是使用concatMap告诉配方 Observable,一旦这个可观察量完成,我需要将其与另一个可观察量映射,然后使用forkJoin来获取每个配方成分的完整表示,最后将这些结果映射回原始配方。

最新更新