簡體   English   中英

Angular - 從多個請求中獲得響應

[英]Angular - get response from more than one request

我需要觸發 2 個請求。 基於第一個,我需要觸發第二個,最后從兩個請求返回響應:

  getDetails(userName: string) {
    this.rep$ = this.http.get<IRep[]>(`${this.api}/users/${userName}/coll1`);
    return this.rep$.pipe(switchMap(repos => {
      return repos.filter((repo) => {
        return repo.active === false;
      }).map((repo) => {
        return this.http.get<IColl2[]>(`${this.api}/repos/${userName}/${repo.name}/coll2`);
      });
    }, (resp1, resp2) => [resp1, resp2])
    );

  }

對於您需要的內容,您可以使用combineLatest等待所有第二個請求並將第一個請求結果添加到它們中:

getDetails(userName: string) {
    this.rep$ = this.http.get<IRep[]>(`${this.api}/users/${userName}/coll1`);
    return this.rep$.pipe(switchMap(repos => {
      const inactiveRepos = repos.filter((repo) => !repo.active);
      combineLatest(
        inactiveRepos.map((repo) => this.http.get<IColl2[]>(`${this.api}/repos/${userName}/${repo.name}/coll2`))
      ).pipe(
        map((responses) => responses.map((response) => ({response1: repos, response2: response})))
      )
    }
}

在上面的示例中,結果將是一個數組,對於每個元素,該數組將在屬性 response1 中具有第一個響應,在 response2 屬性中具有第二個響應。

更新

我忘了在 combineLatest 中添加 return 語句:

getDetails(userName: string) {
    this.rep$ = this.http.get<IRep[]>(`${this.api}/users/${userName}/coll1`);
    return this.rep$.pipe(switchMap(repos => {
      const inactiveRepos = repos.filter((repo) => !repo.active);
      return combineLatest(
        inactiveRepos.map((repo) => this.http.get<IColl2[]>(`${this.api}/repos/${userName}/${repo.name}/coll2`))
      ).pipe(
        map((responses) => responses.map((response) => ({response1: repos, response2: response})))
      )
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM