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:
http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http
You can also call toPromise()
on an Observable and convert it to a regular promise as well.
I recommend using Observables for Angular 2+ but in case you still need to use Promises you can use the following:
Promise.all(
[
promise1,
promise2,
promise3
]
);
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