2017-05-09 212 views
0

我試圖重構一些我編寫的代碼,然後合併所有可觀察對象以同時接收聊天對象。我使用角和離子和firebase。如何合併一系列可觀察對象內的觀察對象

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返回爲可觀測量,然後我有使用一個異步管解開所需的對象。有沒有辦法將其全部轉換爲一個可觀察的項目?

回答

0

如果我明白你想要什麼正確實現,即一個可觀察團與解開所有的組數據(memberProfiles等),我想你需要在另一個combineLatest添加然後把三個在那裏觀察。

所以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 }; 
    } 
) 

請注意,我已經改變了對象屬性。

希望有幫助