Angular 2 - Chaining http requests

后端 未结 1 1154
天涯浪人
天涯浪人 2020-11-30 09:17

I get a RxJS Observable from an httpService which is the actual http from Angular. Now as soon as I get a postive result from that, I want to process the next http Request w

相关标签:
1条回答
  • 2020-11-30 09:48

    Chaining HTTP requests can be done using flatMap or switchMap operators. Say we want to make three requests where each request depends on the result of previous one:

    this.service.firstMethod()
        .flatMap(firstMethodResult => this.service.secondMethod(firstMethodResult))
        .flatMap(secondMethodResult => this.service.thirdMethod(secondMethodResult))
        .subscribe(thirdMethodResult => {
              console.log(thirdMethodResult);
         });
    

    This way you can chain as much interdependent requests you want.


    UPDATE: As of RxJS version 5.5 pipeable operators were introduced and the syntax has slightly changed:

    import {switchMap, flatMap} from 'rxjs/operators';
    
    this.service
      .firstMethod()
      .pipe(
        switchMap(firstMethodResult => this.service.secondMethod(firstMethodResult)),
        switchMap(secondMethodResult => this.service.thirdMethod(secondMethodResult))
      )
      .subscribe(thirdMethodResult => {
          console.log(thirdMethodResult);
        });
    
    0 讨论(0)
提交回复
热议问题