Rxjs:将两个流合并为一个依赖于另一个流的流

Dan*_*era 3 javascript stream rxjs angular

我有一个流调用一个服务,该服务返回一个流,该流需要请求的原始流的信息.

this.messages$ = this.selectedChat$
.switchMap(chat => this.chatService.subscribeMessages(chat.room))
.map(messages) =>
  messages.map((message: any) => {
    //Here need add information of the chat object
    return message;
  })
);
Run Code Online (Sandbox Code Playgroud)

我看到的所有运算符都可以合并流并稍后将它们分开(比如combineLatest)接收参数,因此,我无法使用原始流信息来调用生成其他流的服务,我不想使用订阅在原始流上并在订阅内返回一个新流,因为它有点乱码.

有什么建议?

Jot*_*edo 5

使用selector function中的switchMap操作:

this.messages$ = this.selectedChat$
.switchMap(chat => this.chatService.subscribeMessages(chat.room), 
(chat,messages)=>({chat,messages})) // create a new object, using the inner observable and the mapped one
.map(data =>
  data.messages.map((message: any) => {
    // Here data.chat has the chat information
    return message;
  })
);
Run Code Online (Sandbox Code Playgroud)

有关switchMap操作员的更多信息,请查看此处