Jake12342134
Jake12342134

Reputation: 1767

Pass result of first observable to observable in switchMap

I'm using a switchMap to link two observables, however I need the result of the first observable to be available inside the second observable so that I can use the result to map the result of the second observable.

What's the syntax to enable using res1 inside of the subscription?

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

Three observables

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

Upvotes: 0

Views: 1892

Answers (1)

martin
martin

Reputation: 96969

You can map the emission from second observable into an array or object. Result selectors wouldn't help you here:

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]) => { ... })

Upvotes: 4

Related Questions