Reputation: 1072
How can I cascade RxJs calls to retrieve data from this contrived service.
First request goes to /customer/1
/customer/:id
Response:
{
Name: "Tom",
Invoices: [1,3],
Orders: [5,6]
}
In the customer response there are 2 InvoiceIds that we use to access second service:
/invoices/:id
Response
{
Id: 1,
Amount: 10
}
In the customer response there are 2 OrderIds that we use to access third service:
/orders/:id
Response
{
Id:2,
Date: '2016-11-12'
}
At the end I would like to kome up with an object looking like this:
{
Name: "Tom",
Invoices: [
{
Id: 1,
Amount: 10
},
{
Id: 3,
Amount: 5
}],
Orders: [
{
Id:5,
Date: '2016-11-12'
},
{
Id:6,
Date: '2016-11-12'
}]
}
How can I pass the ids through the pipeline so that the dependant objects are retrieved.
My gut feeling tells me I should probably use the flatMap operator, but I am totally uncertain how this could all work together.
var ajax = Rx.DOM.getJSON('/api/customers/1')
.flatMap(p => p.Invoices.map(x =>
Rx.DOM.getJSON('/api/invoices/' + x)
));
Upvotes: 3
Views: 2020
Reputation: 96889
This is a typical use-case where you need to construct a response out of several HTTP calls:
const Observable = Rx.Observable;
var customerObs = Observable.create(observer => {
Observable.of({Name: "Tom", Invoices: [1,3], Orders: [5,6]})
.subscribe(response => {
var result = {
Name: response.Name,
Invoices: [],
Orders: [],
};
let invoicesObs = Observable.from(response.Invoices)
.flatMap(id => Observable.of({ Id: Math.round(Math.random() * 50), Amount: Math.round(Math.random() * 500) }).delay(500))
.toArray();
let ordersObs = Observable.from(response.Orders)
.flatMap(id => Observable.of({ Id: Math.round(Math.random() * 50), Amount: Math.round(Math.random() * 500) }).delay(400))
.toArray();
Observable.forkJoin(invoicesObs, ordersObs).subscribe(responses => {
result.Invoices = responses[0];
result.Orders = responses[1];
observer.next(result);
});
});
});
customerObs.subscribe(customer => console.log(customer));
See live demo: https://jsfiddle.net/martinsikora/uc1246cx/
I'm using Observable.of()
to simulate HTTP requests, flatMap()
to turn each invoice/order id into an Observable (another HTTP request) that are reemitted and then toArray()
to collect all values emitted from an operator chain and reemit them in a single array (just because it's convenient).
Operator forkJoin()
waits until all source Observables complete and then emits their last value as an array (so we haw array of arrays in responses
).
See a similar question: Performing advanced http requests in rxjs
Upvotes: 3