Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 - chaining subscribe

Tags:

angular

rxjs

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.

like image 737
kayasa Avatar asked Jun 22 '17 09:06

kayasa


1 Answers

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

like image 51
Faly Avatar answered Oct 17 '22 06:10

Faly