Skip to content Skip to sidebar Skip to footer

Cascading Ajax Calls With RxJs

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

Solution 1:

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


Post a Comment for "Cascading Ajax Calls With RxJs"