Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting multiple HTTP resources concurrently in Angular2

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.

like image 904
Can Guney Aksakalli Avatar asked Dec 15 '15 23:12

Can Guney Aksakalli


People also ask

What is forkJoin in Angular 8?

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.

What can I use instead of forkJoin?

concat() which will handle each observable in sequence.


1 Answers

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);
like image 131
Can Guney Aksakalli Avatar answered Oct 07 '22 23:10

Can Guney Aksakalli