Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining promises in Angular 2

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?

like image 525
user2884505 Avatar asked Dec 02 '22 15:12

user2884505


2 Answers

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.

like image 177
TGH Avatar answered Jan 11 '23 12:01

TGH


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
      ]
);
like image 41
Jeremy Avatar answered Jan 11 '23 12:01

Jeremy