I can handle a single observable result from http.get
with following code:
http.get('/customers/1')
.map((res: Response) => res.json())
.subscribe(customer => this.customer = customer);
Now I have a list of resource IDs like var list:number[] = [1, 4, 7];
that I want to be able to send request for all resources and assign the all resolved items to my array like customers => this.customers = customers
.
ForkJoin. This operator is best used when you have a group of observables and only care about the final emitted value of each. It means that forkJoin allows us to group multiple observables and execute them in parallel, then return only one observable.
concat() which will handle each observable in sequence.
Rx.Observable.forkJoin can do this.
First import Obserable & forkJoin:
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
or import all
import {Observable} from 'rxjs/Rx';
Now join all observables with forkJoin
:
// a set of customer IDs was given to retrieve
var ids:number[] = [1, 4, 7];
// map them into a array of observables and forkJoin
Observable.forkJoin(
ids.map(
i => this.http.get('/customers/' + i)
.map(res => res.json())
))
.subscribe(customers => this.customers = customers);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With