gpt4 book ai didi

rxjs - 使用 rxjs withLatestFrom 函数

转载 作者:行者123 更新时间:2023-12-04 23:03:27 25 4
gpt4 key购买 nike

尝试执行以下应该执行的代码:

  • 检索用户的所有聊天列表
  • 检索所有这些聊天的最后一条消息
  • 检索所有这些聊天的收件人信息
  • 将所有内容合并为一个数组,其中每个项目都是聊天、最后一条消息和收件人信息的组合
     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 中重现

    任何的想法?

    最佳答案

    链条是自下而上构造的。这意味着订单是subscribe() -> withLatestFrom -> switchMap -> do .

    所以在 withLatestFrom尝试订阅 getLastMessages$getRecipients$他们是 undefined因为只有在从 do() 中发生的源 Observable 传播第一个值之后才分配它们。 .

    编辑:

    // 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);
    });

    http://jsbin.com/sulatar/3/edit?js,console

    关于rxjs - 使用 rxjs withLatestFrom 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45388853/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com