使用rxjs将数据添加到http响应 [英] Add data to http response using rxjs

查看:105
本文介绍了使用rxjs将数据添加到http响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个旅行实体,其中包含驾驶员ID. 我可以使用RESTFull端点进行获取旅行,例如/trips/2/.

I have a trip entity which contains driver id. I can get fetch trip using RESTFull endpoint, e.g. /trips/2/.

//example response
{
  id: "2",
  driver_id: "123"
}

我可以使用端点获取驱动程序详细信息.例如/drivers/123/, 我最后的回应是

I can fetch driver details using the endpoint. e.g. /drivers/123/, My final respected response is

//expected response from observable
{
  id: "2",
  driver_id: "123",
  detailed_driver: {
    name: "abc",
    id: "123"
  }
}

目前,我按如下所述进行操作

Currently I do it as follows

this.http("/trips/2/").map(data => data.json()).subscribe(trip => {
   this.http("/drivers/" + trip.driver_id + "/").map(data => data.json()).subscribe(driver => {
      trip.detailed_driver = driver;
      this.trip = trip 
   }
}

如何使用Rxjs使用这两个端点从单个可观察对象获得最终的预期响应?

How can I use Rxjs to use these two endpoints to get final expected response from a single observable?

推荐答案

您可以使用flatMap运算符和Observable.forkJoin,如下所述:

You could use the flatMap operator and Observable.forkJoin as described below:

this.http.get('/trips/someid')
   .map(res => res.json())
   .flatMap(res => {
     return Observable.forkJoin([
       Observable.of(res),
       this.http.get('/drivers/'+res['driver_id']).map(res => res.json())
     ]);
   })
   .map(res => {
     res[0]['detailed_driver'] = res[1];
     return res[0]
   })
 .subscribe(
   (data) => {
   }
 );

flatMap允许在收到第一个请求时执行另一个请求. Observable.forkJoin允许同时接收第一个响应的响应和第二个响应的结果.

The flatMap allows to execute another request when the first one is received. Observable.forkJoin allows to receive both the response of the first response and the result of the second one at the end.

这样,您将可以用第二个结果更新第一个结果...

This way you will be able to update the first result with the second one...

这篇关于使用rxjs将数据添加到http响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆