Angular 4 - chain subscription

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

How can I achieve this chain using Rxjs subscription.

In the code below, I am calling the client's web service to get its pin. When I receive this, only then do I need to call the second rest service with the pin as the 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 correct way to bind a subscription? I need to make another web service after getting the 2nd service results. This will add even more code block.

+3


source to share


1 answer


This will be cleaner using flatMap

, so there is only one subscription:

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 see what it really does take a flatMap

look at this: https://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html

+5


source







All Articles