我可以在类型脚本事件处理程序中ping多个API吗?

时间:2019-05-06 22:29:25

标签: javascript angular typescript

我正在尝试在一个函数中对几个API进行ping操作,但似乎无法弄清楚。我认为这是可行的,因为每个API的单独功能似乎有些极端(当标头和可观察的标头在它们之间相同时)。这是我编写的无效函数,有人对如何处理此函数有任何建议吗?

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;
}

2 个答案:

答案 0 :(得分:3)

您正在寻找的是zip的Observables运算符。它的作用是将您所有的Observable合并为一个,等待所有的Observable都发出值(在您的情况下,返回相应API的响应),然后将所有值作为数组发出。您甚至不需要单独的功能,因为zip运算符会返回您订阅的Observable。

    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
    });

答案 1 :(得分:1)

您可以像这样使用forkJoin

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);
  });