Reputation:
I am trying to use Angular HttpClient
to fetch data from APIs. I have to make many get
requests and all of them are independent. But if even one of them fails, I have to terminate the process. With promises
, it would have been easy, I could have used Promises.all
. But with HttpClient
I am not sure how to do this. At present, I am nesting all of my requests, which seems to me as a bad coding practice. Here is a sample code which I am doing. Please note all my api calls are independent.
self.authService.getDuration().subscribe(
function(data: Array<IDuration>) {
self.duration = data;
self.authService.getUserData().subscribe(
function(data: any){
self.userData = data;
//more api calls in nested manner
},
function(err){
console.log("error");
}
);
},
function(err){
console.log("error");
}
);
Is there a better way to do this, so that I don't have to nest all of my independent api calls and get a failure message if any of the APIs fails?
Upvotes: 1
Views: 80
Reputation: 105
use forkJoin
let character = this.http.get('https://swapi.co/api/people/1');
let characterHomeworld = this.http.get('http://swapi.co/api/planets/1');
forkJoin([character, characterHomeworld])
.subscribe(results => {
//results[0] is our character
//results[1] is our character homeworld
}, err => {
//handle error here
});
Upvotes: 1