angularrxjsrxjs-observablesconcatmap

how to pass data between concatmap in RXJS Angular


I have a pipe on a observable, the code is like below:

.pipe(
concatMap(() => this.security.getUser()),
tap((partyId) => {
    if (!partyId) {
            window.location.assign(`${environment.redirectURL1}/dashboard/login`);
    }
}),
concatMap((partyId) => this.security.getType(partyId)),
tap(async (result) => {
    if (result) {
            this.loggingService.setUser(result.partyId, result.partyType, result.lendingType);
    }else{
            this.loggingService.setUser(partyId, 'null', 'null'); //In here how can I get partyId??
    }
})
)

As you can see, In the last tap the result I am getting have partyId, because I am concatenating partyId which I am sending to the previous concatMap method which is concatMap((partyId) => this.security.getType(partyId)), however, I also want partyId if the result is null as well, so my question is how can I access the partyId in the last concatMap which I am getting from first concatMap which is concatMap(() => this.security.getUser())?


Solution

  • You can add another .pipe() after your other call, so you end up with nested pipes:

    .pipe(
      concatMap(() => this.security.getUser()),
      tap(partyId => {
        if (!partyId) {
           window.location.assign(`${environment.redirectURL1}/dashboard/login`);
        }
      }),
      concatMap(partyId => this.security.getType(partyId).pipe(
        tap(result => {
          if (result) {
            this.loggingService.setUser(result.partyId, result.partyType, result.lendingType);
          } else {
                this.loggingService.setUser(partyId, 'null', 'null');
          }
        })
      ))
    );
    

    This technique is explained in more detail in this answer.