7

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.

2
  • 1
    Check forkJoin Commented Dec 16, 2015 at 0:02
  • thanks @EricMartinez , this solved. Commented Dec 17, 2015 at 1:56

1 Answer 1

9

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer! There's a detailed explanation available here too metaltoad.com/blog/angular-2-http-observables

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.