目前,我遇到了 Firebase Observable 连接的问题。
我真的不知道从不同对象获取数据并将它们连接在一起的最佳方法是什么。
我的数据结构:
users {
userid1 {
conversationid: id
...
},
userid2 {
...
}
}
conversations {
conversationid {
...
}
}
现在我想获取当前用户的所有对话。
要获取当前用户 ID,我将像这样订阅 auth Observable:
this.af.auth.subscribe(auth => {
console.log(auth.uid);
});
接下来我需要用户的子对象来获取对话 ID。我这样做:
//needs the userid from Observable on top
this.af.database.object('/users/' + auth.uid)
.map(
user => {
console.log(user.conversationid);
}
)
.subscribe();
对话也是如此:
//needs the conversationid from the second Observable
this.af.database.list('/conversations/' + user.conversationid)
.subscribe();
如您所见,有 3 个 Observable。我知道可以嵌套它们,但在我的项目中这种情况最多可能发生 5 次。
是否可以在不嵌套 3 个 Observable 的情况下进行对话?
最佳答案
你可以这样做:
let combined = this.af.auth
// Filter out unauthenticated states
.filter(Boolean)
// Switch to an observable that emits the user.
.switchMap((auth) => this.af.database.object('/users/' + auth.uid))
// Switch to an observable that emits the conversation and combine it
// with the user.
.switchMap((user) => this.af.database
.list('/conversations/' + user.conversationid)
.map((conversation) => ({ user, conversation }))
);
// The resultant observable will emit objects that have user and
// conversation properties.
combined.subscribe((value) => { console.log(value); });
关于Firebase 数据与 Observable 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40537453/