0
votes

I'm trying to use RxJS concatMap to sequence my 2 observables so that it returns the employeeID before calling the service to return the object to bind to my Mat-Table in Angular 9. But I'm not sure how to write the syntax correctly. the first observable is actually a behavior subject that I created to let components subscribe to anywhere in the app. the second is an http response from a web api.

I've been looking at the example here and trying to figure it out but just been banging on the keyboard. RxJS concatMap

//first observable (actually a Behavior Subject)
this.userService.currentEmployeeId.subscribe(empId => this.employeeID = empId)

//second observable
this.service.getMissingContractsSummary(this.employeeID)
.subscribe(
  response => {        
    this.dataSource = new MatTableDataSource<Contractsummary>(response);
    this.dataSource.paginator = this.paginator;
  }
);
2

2 Answers

3
votes

Try it the following way:

import { concatMap } from 'rxjs/operators';

this.userService.currentEmployeeId.pipe(
   concatMap(empId => this.service.getMissingContractsSummary(empId)),
).subscribe(response => {
  this.dataSource = new MatTableDataSource<Contractsummary>(response);
  this.dataSource.paginator = this.paginator;
});

There is a difference between concatMap, switchMap, mergeMap. In your example, I think I would switch concatMap for switchMap although most likely for your example using any of the 3 will do the trick.

https://blog.angular-university.io/rxjs-higher-order-mapping/

3
votes

concatMap should work but depending on the behavior you want you may want to try switchMap. In either case, the syntax is similar. You will need to pipe that operation to the currentEmployeeId observable. When that emits a new value, the switchMap function can pass the value to your service's get function to return that observable. Then you can subscribe as you already have in your example code.

this.userService.currentEmployeeId.pipe(
  switchMap(empId => this.service.getMissingContractsSummary(empId))
).subscribe(response => {
    this.dataSource = new MatTableDataSource<Contractsummary>(response);
    this.dataSource.paginator = this.paginator;
})

P.S. Don't forget to unsubscribe, since it looks like currentEmployeeId may not complete.