Angular-从多个请求中获取响应

时间:2020-03-20 18:14:52

标签: angular rxjs observable

我需要触发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])
    );

  }

1 个答案:

答案 0 :(得分:2)

对于您需要的内容,可以使用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属性中具有第二个响应。

更新

我忘记将return语句添加到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);
      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})))
      )
    }
}