3

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"
}

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 
   }
}

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

1
  • can you add your current fetch code? Commented Mar 11, 2016 at 10:21

1 Answer 1

4

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) => {
   }
 );

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

Sign up to request clarification or add additional context in comments.

4 Comments

what's wrong in here plnkr.co/edit/opyzLR4ejKdLPGfWM7EN?p=preview click on friend tab and look at frineds.ts. I tried to implement your suggested code but not working with no error.
In fact, there is a typo in my code :-( The } at the end of the forkJoin... I updated my answer and fixed your plunkr: plnkr.co/edit/BthgxpehFcR6fg9hBRMj?p=preview. Thanks for pointing this out @micronyks!
But I can't find required data in object console.log(data) . Could you please help me?
its worked! thanks... I needed to make few changes, like addedin .map()res => res.json() in the second this.http.get() and return res[0] in the final map function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.