Craig
Craig

Reputation: 153

Can I ping multiple API's in a type-script event handler?

I am trying to ping a few API's in one function but can't seem to figure it out. I assume this is possible, because a separate function per API seems a bit extreme (when the headers and observable are the same among them). Here is an invalid function that I wrote, does anyone have any advice on how to handle this?

getAPIs(unit: string): Observable<myObservable> {
    const headers = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': '*',
            'Authorization': 'Bearer xxxxxyyyyyzzzzz',
        })
    };

    const firstAPI = this.httpClient.get<myObservable>(this.firstAPIurl, headers);
    const secondAPI = this.httpClient.get<myObservable>(this.secondAPIurl, headers);
    const thirdAPI = this.httpClient.get<myObservable>(this.thirdAPIurl, headers);
    const fourthAPI = this.httpClient.get<myObservable>(this.fourthAPIurl, headers);

    return firstAPI, secondAPI, thirdAPI, fourthAPI;
}

Upvotes: 1

Views: 99

Answers (2)

Hien Nguyen
Hien Nguyen

Reputation: 18973

You can use forkJoin for your requirement like this

forkJoin(
  {
    first: this.httpClient.get<myObservable>(this.firstAPIurl, headers),
    second: this.httpClient.get<myObservable>(this.secondAPIurl, headers),
    third:  this.httpClient.get<myObservable>(this.thirdAPIurl, headers),
    fourth: this.httpClient.get<myObservable>(this.fourthAPIurl, headers)
  }
)
  .subscribe(result => {
    console.log(result.first);
    console.log(result.second);
    console.log(result.third);
    console.log(result.fourth);
  });

Upvotes: 0

Stromwerk
Stromwerk

Reputation: 780

What you are looking for is the zip operator for Observables. What it does is take all your Observables, combines them into one, waits untill all of them have emitted values (returned responses from the respective APIs in your case) and then emits all the values as an array. You don't even need a separate function, as the zip operator returns an Observable to which you subscribe to.

    const zippedAPIs = zip(
        this.httpClient.get<myObservable>(this.firstAPIurl, headers),
        this.httpClient.get<myObservable>(this.secondAPIurl, headers),
        this.httpClient.get<myObservable>(this.thirdAPIurl, headers),
        this.httpClient.get<myObservable>(this.fourthAPIurl, headers)
    );

    // Then you would subscribe to the new Observable created by zip
    zippedAPIs.subscribe(results => {
        console.log(results[0]); // result from firstAPI
        console.log(results[1]); // result from secondAPI
        console.log(results[2]); // result from thirdAPI
        console.log(results[3]); // result from fourthAPI
    });

Upvotes: 3

Related Questions