Merge different HTTP calls which are dependent on each other in RxJS/Angular 6

不羁的心 提交于 2021-02-18 14:52:35

问题


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.

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?

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

Both functions (getPostData and getUserByPostData) will return Observables due to http.get

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).

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?


回答1:


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

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.



来源:https://stackoverflow.com/questions/50357820/merge-different-http-calls-which-are-dependent-on-each-other-in-rxjs-angular-6

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!