Sekrab Garage

RXJS observables

RXJS: passing values down a chain

Tip July 1, 20

When chaining an observable, and needing the value of a step, to be carried forward and used in another step, map the internal observable into a new object, before passing it on. Here is how:

// get initial observable and pipe
const o1$ = initial$.pipe(
    switchMap(data => {
      const abc = data.abc;
      
      // get new data using the value of abc
      return getsomeObservable(abc).pipe(
        map(innerdata => {
          // map it using abc
            return {
              abc: abc, // carried down the chain
              moredata: innerdata
            };
        })
      );
    }),
    tap(finaldata => {
      console.log(finaldata);
      // this should give {abc, moredata}
    })
  );