将多个firebase可观察对象组合成一个可观察的

时间:2017-04-24 17:56:21

标签: angular firebase ionic2 rxjs observable

我有一个firebase聊天应用程序,其中一个对话在两个用户之间,具有以下数据结构:

Users {
    user1 {
        profile {...} 
        conversations {
             12345co: true
             12346co: true
        }
        conversationsWith {
            user2: "12345co"
            user3: "12346co"
        }
    }
    user2 {
        profile {
             name: 'Jane',
             mainImg: imgData,
             ages: 25
        } 
        conversations {
             12345co: true
        }
         conversationsWith {
            user1: "12345co"
        }
    }
    user3 {
        profile {
             name: 'John',
             mainImg: imgData,
             ages: 22
        } 
        conversations {
             12346co: true
        }
         conversationsWith {
            user1: "12346co"
        }
    }
}
Conversations {
    conv1 {...}
    conv2 {...}
}

我希望能够组合来自用户和会话节点的数据,最终得到一个可观察对象的观察点:

convProfObj {
    recipientProfile {
         name: "Jane",
         age: 25,
         mainImg: imgData
    }
    conversation: "conv1"
}

目前我正在尝试以下内容,但最终的convProfiles数组只包含相同的convProfile对象X次,其中X =用户拥有的对话数:

getConversations2(fbid){
    let me = this;
    var profiles = [];
    var convObject;
    var conversations = this.af.database.list("Users/"+fbid+"/ConversationsWith", {preserveSnapshot: true});
    conversations.subscribe(snapshot=>{
      convObject =  {
        conversation: null,
        recipProfile: null,
        lastMessage: 1,
        creationDate: 1
      };
      snapshot.forEach(snap => {
        var convID = snap.val();
        convObject.conversationID = convID;
        var profile = me.af.database.object("Users/"+snap.key+"/Profile", { preserveSnapshot: true });
        profile.subscribe(snap2=> {
          convObject.recipProfile = snap2.val();
          profiles.push(convObject);
        })
      });
    })
    console.log(profiles);
    return profiles;
  }

我的模板是这样的:

<ion-item *ngFor="let conv of conversations | async" (click)="viewConversation(conv)">
  <ion-avatar item-left>
    <img src="data:image/png;base64,{{conv.recipProfile.mainImg}}">
  </ion-avatar>
  <h2>{{conv.recipProfile.name}}</h2>
  <p>{{conv.conversationID}}</p>
</ion-item>

Screengrab of final output - should be 2 different conversation items, not the same one twice

0 个答案:

没有答案