简体   繁体   中英

Angular - get response from more than one request

I need to trigger 2 requests. 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:

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.

UPDATE

I forgot to add the return statement to the 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})))
      )
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM