首页 > 解决方案 > 将第一个 observable 的结果传递给 switchMap 中的 observable

问题描述

我正在使用 switchMap 来链接两个 observable,但是我需要第一个 observable 的结果在第二个 observable 中可用,以便我可以使用结果来映射第二个 observable 的结果。

res1在订阅内部启用使用的语法是什么?

this._signalRService.obs1.pipe(
          takeUntil(this.destroyObservables),
          switchMap(res1 => {
                  if (this.idParam === res1) {
                      return this.getAllCustomCategoryGroups$();
                  }
                  return;
              }
          )).subscribe(groups => {
            let x = groups.map(group => groupId === res1); //res1 needed here to map groups 
      });

三个可观察的

 this._authService.loggedInUser$.pipe(switchMap((loggedInUser: LoggedInUser) => {
      return this._userSerialService.getUserSerial().pipe(switchMap(serial => {
          return this._usersService.getCurrentUser().pipe(switchMap(currentUser => [loggedInUser, currentUser, serial]))
        }),
      );
    })).subscribe(res => {
      console.log(res);
    })

标签: javascriptrxjs

解决方案


您可以将第二个 observable 的发射映射到数组或对象中。结果选择器在这里对您没有帮助:

switchMap(res1 => {
  if (this.idParam === res1) {
    return this.getAllCustomCategoryGroups$().pipe(
      map(res2 => [res1, res2]),
    );
  }
  return EMPTY; // You have to return something here
}).subscribe(([res1, res2]) => { ... })

推荐阅读