在可观察范围内使用可观察角度 [英] angular using an observable within an observable
问题描述
我正在制作角度为6的费用管理器Webapp.我的数据库位于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()})));}
返回可观察到的费用的函数是
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);
我想创建一个获取支出数组并为每个支出返回类别的可观察对象,我可以将其推入类别数组.我一直在绞尽脑汁,将这两个可观察到的东西与各种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);
但是它只是发出一个Observables数组.如何获取类别对象并将其推入数组?
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())
}
这篇关于在可观察范围内使用可观察角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!