1

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?

2
  • 3
    learnrxjs.io/operators/combination/forkjoin.html. Also, use arrow functions rather than anonymous functions, and stop using this self dirty trick. Commented Jul 17, 2018 at 6:17
  • 1
    @JBNizet Thanks, forkjoin was exactly what I was looking for. Commented Jul 17, 2018 at 6:41

1 Answer 1

1

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
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.