Angular Firebase-将两个Observable合并为一个 [英] Angular Firebase - merge two Observables into one
问题描述
在这里苦苦挣扎太久了.我在Firebase中有两个表:
Struggling a bit too long here. I have two tables in Firebase:
accounts
LJHGGKJH
prop1: 'val'
prop2: 'val'
IUYIUTJF
prop1: 'val'
prop2: 'val'
locations_per_account
LJHGGKJH
0: [1, 5, 6]
IUYIUTJF
0: [5, 2, 8]
您会看到 accounts
项的唯一键指向 locations_per_account
项的唯一键-如果它们匹配,则它们属于同一用户.
As you see accounts
item's unique key points to locations_per_account
item's unique key - if they match they belongs to the same user.
现在,我想在服务中建立一种方法,使我可以观察到每个帐户及其位置,因此可以在模板中使用 async
管道并提取数据.
Now I want to make one method in my service which would provide me observable of every account and its locations, so I could use async
pipe in my template and extract the data.
我在这里拥有所有帐户:
Here I get all accounts:
getAllAccounts() {
return this.afDb.list('accounts/', {
query: {
orderByChild: 'hasAccount',
equalTo: true
}
})
}
我在这里获得特定帐户的位置:
Here I get locations of particular account:
getAccountLocations(optionalUid : string) {
let uid : any;
this.authService.authInfo$.subscribe(val => uid = val.$uid);
if (typeof optionalUid === 'undefined')
return this.afDb.object('locations-per-account/' + uid);
return this.afDb.object('locations-per-account/' + optionalUid);
}
因此,我需要将这些流合并为一个,并通过合并来构造返回对象的新形状.
So I need to merge these streams into one and by merging I should construct the new shape of returning object.
(两个表的顺序是对称的(如果那是正确的词),但是我不确定将来是否会保持不变,所以我想检查两个键是否匹配).
(the order of both tables is symmetric (if thats the right word), but I am not sure if it will stay the same in the future, so i would like to check if both keys match).
还要注意-如您所见,我可以向每个帐户添加locations数组,但是我在单独的表中执行此操作,因为我尝试使Firebase数据库尽可能平坦,以避免出现全表扫描"之类的事情.如果有任何想法,请提出建议-我在建立数据库方面还很陌生.
Also to note - as you see, I could add locations array to every account, but I do it in separate table because I try to make my Firebase database as flat as possible, to avoid things like "Full table scan". Please advice if any thoughts - I am pretty new in building databases.
推荐答案
使用forkJoin等待两个查询,然后将两个集合映射到id上:
Use forkJoin to wait for both queries, then map the two sets together on id:
Rx.Observable.forkJoin([accounts$, locations$]).subscribe(results => {
const [accounts, locations] = results
const joined = accounts.map(account => {
return {
id: account.id,
prop1: account.prop1,
prop2: account.prop2,
locations: locations.filter(location => location.id === account.id)[0].loc };
})
console.log(joined);
});
这假定Firebase为每个查询都发出一个值,每个查询都是一个数组(我认为确实是从文档中得出的一个数组).
This presumes that Firebase is emitting a single value for each query, each of which is an array (which I think it does, from the docs).
还假定每个ID都有一个帐户和位置,否则,映射将变得更加复杂.
Also presumes one account and location per id, if not then the mapping would need to get more complicated.
这是一个模拟场景的CodePen. CodePen
Here's a CodePen which simulates the scenario. CodePen
这篇关于Angular Firebase-将两个Observable合并为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!