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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With