Orl*_*ter 4 observable rxjs firebase firebase-realtime-database angularfire2
目前,我遇到了Firebase Observable加入的问题.
我真的不知道哪种方法可以从不同的对象中获取数据并将它们连接在一起.
我的数据结构:
users {
userid1 {
conversationid: id
...
},
userid2 {
...
}
}
conversations {
conversationid {
...
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想得到当前用户的所有对话.要获取当前用户ID,我将订阅auth Observable,如下所示:
this.af.auth.subscribe(auth => {
console.log(auth.uid);
});
Run Code Online (Sandbox Code Playgroud)
接下来我需要用户的子对象来获取会话ID.我是这样做的:
//needs the userid from Observable on top
this.af.database.object('/users/' + auth.uid)
.map(
user => {
console.log(user.conversationid);
}
)
.subscribe();
Run Code Online (Sandbox Code Playgroud)
对话也一样:
//needs the conversationid from the second Observable
this.af.database.list('/conversations/' + user.conversationid)
.subscribe();
Run Code Online (Sandbox Code Playgroud)
如您所见,有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); });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1910 次 |
| 最近记录: |