问题描述
我正在制作一个 angular 6 的费用管理器 web 应用程序.我的数据库在 firebase 上.我正在使用 angularfire2 lib 来检索和更新数据.
I am making an expense manager webapp with angular 6. My database is on firebase. I am using the angularfire2 lib to retrieve and update the data.
数据库设计如下
获取类别的函数是
getCategory(uid:String,categorykey:string):Observable<any>
{
return this.afdb.object(`users/${uid}/categories/${categorykey}`)
.snapshotChanges()
.pipe(map(c=>({key:c.payload.key,...c.payload.val()})));}
返回带有费用数组的 observable 的函数是
the function that returns observable with an array of expenses is
getExpensesWithKeys(uid:String):Observable<any>{
return this.afdb.list(users/${uid}/expenses)
.snapshotChanges()
.pipe(
map(changes =>
changes.map(c =>
({key:c.payload.key,...c.payload.val()}))
)
);
}
在我的组件中,我可以得到我的费用
In my component I can get my expenses as
expenses:Expense[];
getExpensesWithKey("userid-123")
.subscribe(expenses=>this.expenses=expenses)
和任何类别
category:Category;
getCategory("userid-123",expenses[0].category)
.subscribe(category=>this.category=category);
我想创建一个 observable,它获取费用数组并返回每个费用的类别,我可以将其放入类别数组中.我一直在绞尽脑汁将这两个 observable 与各种 rxjs 操作符结合起来,但无济于事.
I want to create an observable that gets the expenses array and returns the category for each expense which i can push into an array of categories.I've been racking my brain to combine the two observables with all kinds of rxjs operaters but to no avail.
非常感谢您的帮助.
只是想添加一些我已经尝试过的方法.我尝试过的一种方法是
edit:Just wanted to add a few methods I tried already.One method I tried was
this.getExpensesWithKeys("user-123")
.pipe(mergeMap(expenses=>
expenses.map(expense=>
this.getCategory("user-123",expense.category)))).subscribe(console.log);
但它只是发出一个 Observable 数组.如何获取类别对象并将它们推送到数组中?
but it just emitting an array of Observables. How can i get the category objects and push them into an array?
我试过的另一种方法
this.rtdbService.getExpensesWithKeys("user-123")
.pipe(map(expenses=>
expenses.map(expense=>expense.category)))
.pipe(mergeMap(ids=>
this.rtdbService.getCategory("user-123",ids)))
.subscribe(console.log);
这只是发出类别的键.
我也尝试了下面提供的答案,但没有发出任何内容.
I also tried the below provided answer as well which is not emitting anything.
提前致谢
推荐答案
我终于找到了解决方案
getExpensewithCategories(uid:String):Observable<any>{
;
let expwithCat$=this.getExpenses(uid).pipe(mergeMap(expenses =>{
return expenses.map(expense => this.getCategory(uid,expense.category)
.pipe(map(cat=>
({expensekey:expense.key,
amount:expense.amount,
date:expense.date,
expcatkey:expense.category,
categorykey:cat.key,
color:cat.color,
name:cat.name})
)
))
}
}));
return expwithCat$.pipe(mergeAll())
}
这篇关于在 observable 中使用 observable 的角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!