将2个流与每个订阅操作组合

时间:2018-07-04 08:39:12

标签: angular rxjs

我有以下这段代码,它们执行相同的操作,但要使用两个不同的ID:

此部分用于检索我的线程对象:

this.route.paramMap
  .pipe(
    map(params => this.threadId = params.get('threadId')),
    switchMap(threadId => this.threadsStoreService.threads
      .pipe(map(threads => threads.find(threadItem => threadItem._id === threadId))))
  )
  .subscribe(thread => this.thread = thread);

此部分用于检索我的消息对象:

this.route.paramMap
  .pipe(
    map(params => this.messageId = params.get('messageId')),
    switchMap(messageId => this.messagesStoreService.messages
      .pipe(map(messages => messages.find(messageItem => messageItem._id === messageId))))
  )
  .subscribe(message => this.message = message);

因为我需要订阅每个流才能检索对象(线程和消息),所以我想知道是否可以将这些流组合在一起吗? 我尝试了forkJoin,但没有成功。

预先感谢您的回答。

2 个答案:

答案 0 :(得分:2)

您可以考虑使用tap运算符(以前称为do)。

tap允许您在管道链中的任意位置添加观察者。

因此,您可能会遇到类似的情况

收藏夹

我有以下这段代码,它们执行相同的操作,但要使用两个不同的ID:

此部分用于检索我的线程对象:

const thread$ = this.route.paramMap
  .pipe(
    map(params => this.threadId = params.get('threadId')),
    switchMap(threadId => this.threadsStoreService.threads
      .pipe(map(threads => threads.find(threadItem => threadItem._id === threadId)))),
    tap(thread => this.thread = thread)
  );

const message$ = this.route.paramMap
  .pipe(
    map(params => this.messageId = params.get('messageId')),
    switchMap(messageId => this.messagesStoreService.messages
      .pipe(map(messages => messages.find(messageItem => messageItem._id === messageId)))),
    tap(message => this.message = message)
  );

merge(thread$, message$).subscribe()

答案 1 :(得分:1)

您可以将数据合并到一个数组中,并获得线程和消息。在此示例中,您必须填写“线程”和“消息”的类型。

type SubscriptionOutputTypes = [<insert thread type here> , <insert message type here>];
this.route.paramMap
  .pipe(
    map(params => {
      this.threadId = params.get('threadId');
      this.messageId = params.get('messageId')
    }),
    switchMap( _ =>
              zip(
                this.threadsStoreService.threads.pipe(map(threads => threads.find(threadItem => threadItem._id === this.threadId)))
                ,
                this.messagesStoreService.messages.pipe(map(messages => messages.find(messageItem => messageItem._id === this.messageId)))
              )
             )
  )
  .subscribe( ([thread, message] : SubscriptionOutputTypes) => {
    this.thread = thread;
    this.message = message;
  });