RxJs结合http请求

时间:2019-06-15 03:42:29

标签: javascript angular typescript rxjs

我正在尝试在rxjs帮助中合并两个HTTP请求以合并请求,但是第二个请求的参数(accountId,userId)在第一个请求的响应中。

a = http.get<any>(...);
b = http.get<any>(... +  '/' + accountId + '/' + userId})

concat(a, b).subscribe(res => {});

3 个答案:

答案 0 :(得分:1)

您可以使用mergeMap,因为您在第一个api请求的响应中说accountId和userId。

a.pipe(
 mergeMap(data => b(data.accountId,data.userId))
).subscribe(response => console.log(response));

您应在其中将b定义为返回可观察值的东西

b(accountId userId): Observable<any> {
 return http.get<any>(... +  '/' + accountId + '/' + userId)
}

答案 1 :(得分:0)

您可以使用forkJoin合并多个订阅。

forkJoin([a, b]).subscribe((res) => {
  // res[0] should be the response of `a`
  // res[1] should be the response of `b`
});

答案 2 :(得分:0)

您可以简单地通过响应将数据向下传递。

a = http.get<any>(...);
b = http.get<any>(... +  '/' + accountId + '/' + userId})
const getBFromA$ = a.pipe(
    switchMap((aResponse) => {
        const accountId = aResponse.accountId;
        const userId = aResponse.userId;
        return http.get<any>(... +  '/' + accountId + '/' + userId})
    }).subscribe((bResponseOnly) => { // do something if you want to })