尝试执行以下代码:
将所有项合并为一个数组,其中每个项目都是聊天,上一条消息和收件人信息的组合
this.msgService.getUserChatList(this.uid).do((chats) => {
this.chats = [];
if (!(chats.length > 0))
this.loading = false;
this.getLastMessages$ = this.getLastMessagesForChats(chats);
this.getRecipients$ = this.getRecipientsForChats(chats);
}).switchMap( chats => Observable.from(chats) ).withLatestFrom(
this.getLastMessages$,
this.getRecipients$,
(chat, lastMessages, recipients) => ({
chat: chat,
last: lastMessages[chat['id']],
recipient: recipients[chat['id']]
})
).subscribe( chats => {
console.log('chats ', chats);
this.chats.push(chats);
this.loading = false;
});
附加功能
getLastMessagesForChats(chats: any): Observable<any[]> {
let lastMessages$ = [];
for (let chat of chats) {
let obs = this.msgService.getLastMessage(chat.id)
.map( last => ({chat: chat.id, last: last}) );
lastMessages$[chat.id] = obs;
}
return Observable.from(lastMessages$).merge().toArray();
}
getRecipientsForChats(chats: any): Observable<any[]> {
let recipients$ = [];
for (let chat of chats) {
let obs = this.userService.getUserPublicInfo(chat.recipient)
.map( recipient => ({chat: chat.id, recipient: recipient}) );
recipients$[chat.id] = obs;
}
return Observable.from(recipients$).merge().toArray();
}
我收到以下错误
Uncaught (in promise): TypeError: Cannot read property 'subscribe' of undefined
TypeError: Cannot read property 'subscribe' of undefined
我找不到出错的地方......我试图在以下JSBIN
中重现有什么想法吗?
答案 0 :(得分:2)
链条是自下而上构建的。这意味着订单为subscribe()
- &gt; withLatestFrom
- &gt; switchMap
- &gt; do
。
因此,在withLatestFrom
尝试订阅getLastMessages$
和getRecipients$
时,它们是undefined
,因为只有在第一个值从源Observable传播后才会分配它们这发生在do()
。
编辑:
// Execution
getLastMessages$ = Rx.Observable.of(1);
getRecipients$ = Rx.Observable.of(2);
chats = [];
getUserChatList('uC')
.do( (chats) => {
getLastMessages$ = getLastMessagesForChats(chats);
getRecipients$ = getRecipientsForChats(chats);
} )
.switchMap( chats => Rx.Observable.from(chats) )
.withLatestFrom(
getLastMessages$,
getRecipients$,
(chat, lastMessages, recipients) => ({
chat: chat,
last: lastMessages[chat['id']],
recipient: recipients[chat['id']]
}))
.subscribe( c => {
console.log('chats ', c);
chats.push(c);
});