合并在 RxJS/Angular 6 中相互依赖的不同 HTTP 调用 [英] Merge different HTTP calls which are dependent on each other in RxJS/Angular 6
问题描述
我已经尝试找到这个答案有一段时间了,但作为 RxJS 和 Angular (2+) 的新手,我正在寻找一种方法来组合两个 HTTP GET 调用的结果.一次调用完成后,必须根据该结果进行新调用.第一次调用的结果将与第二次调用相结合.最好在以对象为类型的属性中.
I've been trying to find this answer for a while now, but I, as a new person to RxJS and Angular (2+), am looking for a way to combine the results of two HTTP GET calls. Once one call has finished, a new call has to be done based on that result. The result of the first call will be combined with the second call. Preferably in a property which has an object as type.
我一直在玩mergeMap
、switchMap
和concatMap
.根据文档和指南,这些功能应该做我想要实现的.但是如何?
I have been playing with mergeMap
, switchMap
and concatMap
. According to the documentation and guides these functions should do what I want to achieve. But How?
在我的示例中,我有一个 ID(例如 3).这是我的代码:
In my example I have got an ID (3 for example). This is my code:
this.postsService.getPostData(postId)
.switchMap(
postData => Observable.forkJoin(this.getUserByPostData(postData))
)
.subscribe( result => console.log(result) );
两个函数(getPostData
和 getUserByPostData
)都将返回 Observables 由于 http.get
Both functions (getPostData
and getUserByPostData
) will return Observables due to http.get
在这种情况下,特别是由于 forkJoin
,我希望我的结果被合并.然而,我检索到的结果已经被第二次请求的结果(即switchMap函数中的那个)完全替换了.
In this case, especially due to forkJoin
, I'd expect my result to be merged. However, the result which I retrieve has been completely replaced with the result of the second request (which is the one inside the switchMap function).
我如何才能合并结果?是否也可以将第二个 HTTP 请求 (this.getUserByPostData
) 的结果作为第一个请求结果的属性推送?
How would I be able to combine the results? Would it also be possible to push the results of the second HTTP request (this.getUserByPostData
) as a property of the results of the first request?
推荐答案
如果第二个请求依赖于第一个请求的响应中的数据,并且如果您想组合两个响应,则可以在 switchMap
中使用 map
运算符:
If the second request depends upon data in the response from first request and if you want to combine the two responses, you can use a map
operator within the switchMap
:
this.postsService.getPostData(postId).switchMap(
postData => this.getUserByPostData(postData).map(
userByPostData => ({ postData, userByPostData })
)
).subscribe(({ postData, userByPostData })=> console.log(postData, userByPostData));
此外,如果 getPostData
返回的 observable 是基于 HTTP 的,它只会发出一次,因此永远不需要切换.您可以改为使用 mergeMap
.
Also, if the observable returned by the getPostData
is HTTP-based, it will only ever emit once, so there will never be any need to switch. You could just use mergeMap
, instead.
这篇关于合并在 RxJS/Angular 6 中相互依赖的不同 HTTP 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!