Home > Back-end >  How to chain variable number of observables?
How to chain variable number of observables?

Time:11-21

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

CodePudding user response:

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

CodePudding user response:

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))
);
  • Related