Is there any way to combine promises in AngularJS 2?
In Angular 1, for instance, I would use $q.all
to combine multiple requests into a single promise.
Is there an equivalent for Angular 2?
The http module works in terms of Observables which is different than promises, but you can do both chaining and parallel calls.
Chaining can be done using flatMap
and parallel calls can be handled using forkJoin
.
Examples:
//dependent calls (chaining)
this.http.get('./customer.json').map((res: Response) => {
this.customer = res.json();
return this.customer;
})
.flatMap((customer) => this.http.get(customer.contractUrl)).map((res: Response) => res.json())
.subscribe(res => this.contract = res);
//parallel
import {Observable} from 'rxjs/Observable';
Observable.forkJoin(
this.http.get('./friends.json').map((res: Response) => res.json()),
this.http.get('./customer.json').map((res: Response) => res.json())
).subscribe(res => this.combined = {friends:res[0].friends, customer:res[1]});
You can find more details and a demo here: Angular and Http
You can also call toPromise()
on an Observable and convert it to a regular promise as well.