简体   繁体   English

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

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

I need to trigger 2 requests.我需要触发 2 个请求。 Based on the first one I need to trigger the second one, and at the end return response from both requests:基于第一个,我需要触发第二个,最后从两个请求返回响应:

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

  }

For what you need you can use combineLatest to wait for all the second requests and the add the first request result to them:对于您需要的内容,您可以使用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})))
      )
    }
}

In the above exemple the result will be an array that for each element will have the first response in the property response1 and the second response in the response2 property.在上面的示例中,结果将是一个数组,对于每个元素,该数组将在属性 response1 中具有第一个响应,在 response2 属性中具有第二个响应。

UPDATE更新

I forgot to add the return statement to the combineLatest:我忘了在 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