繁体   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