Simon Trewhella Simon Trewhella - 27 days ago 12
Javascript Question

RxJS Array of urls to GET requests merged

I'm brand new to RxJS and want to do the following (in Angular 2):


  1. Request some JSON from the server containing an array of urls

  2. Make a request to each of those urls

  3. Subscribe to the combined completion of all of those requests



At the moment my method looks like this:

load():void {
this.http.get(SVG_LIST)
.map(res => {
return <Array<string>> res.json().files;
})
.catch(this.handleError);
}


What do I chain onto the
map
method?

Answer

You are looking for the equivalent of Promise.all, which is the operator forkJoin. You could try something like :

load():void {
        this.http.get(SVG_LIST)
            .map(res => {
                return <Array<string>> res.json().files;
            })
            .flatMap(files => Rx.Observable.forkJoin(files.map(makeRequest)))
            .catch(this.handleError);
    }

where files is an array of urls, makeRequest is a function which takes an url and returns an observable or a promise.