我试图重构一些代码,我后来写了一段时间来合并我所有的observable同时接收聊天对象。我使用角度和离子以及火焰基地。
this.userAsync = this.chatsProvider.getMyUserChatsGrpID().mergeMap(grpIDs=> {
if (grpIDs.length > 0) {
return Observable.combineLatest(
grpIDs.map((grpID) => this.chatsProvider.getGroupObjectAsync(grpID.$key).map(grpObject => {
grpObject.object = grpObject;
grpObject.memberProfiles = this.chatsProvider.getMemberProfiles(Object.keys(grpObject.members))
grpObject.latestMessage = this.chatsProvider.getLatestConversation(grpID.$key, grpObject.lastChecked)
grpObject.unreadMessages = this.chatsProvider.getUnreadMessageCount(grpID.$key, this.profileService.getUIDString())
return grpObject
})),
)
} else {
return Observable.of([])
}
目前这样的代码将返回所需的对象,但是grpObject.memberprofiles,.lastestMessage,.unreadMessages作为observable返回,然后我必须使用异步管道解包。有没有办法将它全部转换成一个可观察的项目?
答案 0 :(得分:0)
使用toArray()运算符。 http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-toArray
let obs1$= Rx.Observable.of(1,2,3);
let obs2$= Rx.Observable.of('A','B','C');
obs2$.concat(obs1$).toArray().subscribe(x=>console.log(x))
答案 1 :(得分:0)
如果我已经理解了你想要正确实现的目标,即一个包含所有组数据(memberProfiles等)的组的可观察组件,我认为你需要添加另一个combineLatest然后将三个observable放在那里。 / p>
所以在grpIDs.map循环中你需要这个
return this.chatsProvider.getGroupObjectAsync(grpID.$key).combineLatest(
this.chatsProvider.getMemberProfiles(Object.keys(grpObject.members)),
this.chatsProvider.getLatestConversation(grpID.$key, grpObject.lastChecked),
this.chatsProvider.getUnreadMessageCount(grpID.$key, this.profileService.getUIDString()),
/* Function which gets passed all the latest observable values for you to merge together*/
(group, members, latestConversation, unreadMessageCount) => {
return { group, members, latestConversation, unreadMessageCount };
}
)
请注意,我已更改了对象属性。
希望有所帮助