kayasa
kayasa

Reputation: 2085

Angular 4 - chaining subscribe

I am calling a webservice from Angular 4 code and subscribing to the response. When the response comes, I need to parse it and using the parsed information call another webservice (and then subscribe to the response once again).

How can I achieve this chaining using Rxjs subscribe.

In the below code, I am calling a customer web service to get his pin code. When I get that, only then I need to call the 2nd rest service with pin code as an input.

fetchCoordinates() {

    this.myService.get('http://<server>:<port>/customer')
      .subscribe(
      (response: Response) => {

        let pinUrl = JSON.parse(response.text()).items[0].pin;
        // Take the output from first rest call, and pass it to the second call
        this.myService.get(pinUrl).subscribe(
          (response: Response) => {
             console.log(response.text()); 
          }
        )
      },
      (error) => console.log('Error ' + error)
      )
  }

Is this the right way of chaining subscribe? I need to do one more web service after results of 2nd services comes back. It would be nesting the code block even further.

Upvotes: 6

Views: 11366

Answers (1)

Faly
Faly

Reputation: 13346

This will be cleaner with the use of flatMap so there is just one subscribe:

this.myService.get('http://<server>:<port>/customer')
.flatMap((response: Response) => { 
    let pinUrl = JSON.parse(response.text()).items[0].pin;
    return this.myService.get(pinUrl);
})
.subscribe((response: Response) => {
    console.log(response.text()); 
});

To understand what flatMap really does, take a look at this: https://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html

Upvotes: 7

Related Questions