How i can deal with a request that depend of other request without using subscribe inside subscribe?

Viewed 113

Nowadays i have one function that makes a http request, when i have the response i do other http request that depends of the success result of the first request.

I have this structure:

  onSubmit() {
    this.service.get().subscribe((res) => {
      this.service2.get().subscribe((res) => {
        console.log(res);
      }, (err) => {
        this.toastr.error(err.statusText);
      })
    }, (err) => {
      this.toastr.error(err.statusText);
    });
  }

I think this is hard to understand and i'm trying to make it in a more appropriete way.

There's a way to extract this in two functions, each with yours errors and concat with some Rxjs operator?

1 Answers

You can use any of the mergeMap, concatMap and switchMap operators. Which one exactly, depends on how many results your first observable will emit, and how you want to handle the situations where the first observable emits again before the 2nd one finished.

onSubmit() {
  this.service.get()
    .pipe(
      .switchMap(result1 => {
        // this will be called once the first call finished, with it's result
        // here you can use the first result
        console.log(`result of the service1 call: ${result1}`);
        // you could even pass it to the 2nd one if it needed it
        // here you have to return an observable
        return this.service2.get();
      }),
      .catchError(err => {
        // you can omit this `catchError`
        // here you can handle errors, but this will receive errors from either of the service calls
        // and you have to return an observable from here too
      })
    ).subscribe(result2 => console.log(`result of service2 call: ${result2}`))
}
Related