1

I am quite new to Angular and Observables. I want to chain the call of a service a certain number of times. Is there a simple way to use Observables? (a bit like that but with a generic manner).

this.myService.getNodeById(res.parent_id).subscribe(res => {
  this.myService.getNodeById(res.parent_id).subscribe(res => {
     this.myService.getNodeById(res.parent_id).subscribe(res => {
        // while res.parents_id exists
     });
  });
});
  • angular: 12.0.5
  • typescript: 4.2.3
  • rxjs: 6.6.0
Ninroot
  • 61
  • 1
  • 8
  • https://stackoverflow.com/questions/43336549/how-to-force-observables-to-execute-in-sequence/43338150#43338150 – martin Nov 20 '21 at 16:48

2 Answers2

1

You could write a recursive function like this:

getNodeById(id) {
  return this.myService
    .getNodeById(id)
    .pipe(switchMap((x) => (x.parent_id ? this.getNodeById(x.parent_id) : of(x))));
}
Guerric P
  • 30,447
  • 6
  • 48
  • 86
0

You can create a custom Rx.js operator which basically calls the required API inside switchMap

type GetNodeFn<TNode = any, TResponse = any> = (
  res: TNode
) => Observable<TResponse>;

// custom getNode operator
function getNode<TNode>(nodeFn: GetNodeFn) {
  return (observable: Observable<TNode>) =>
    observable.pipe(switchMap((res) => nodeFn(res)));
}

this.myService.getNodeById(res.parent_id).pipe(
  getNode((res) => this.myService.getNodeById(res.parent_id)),
  getNode((res) => this.myService.getNodeById(res.parent_id))
);
Aquib Vadsaria
  • 350
  • 4
  • 9