Combining promises in Angular 2

前端 未结 2 1653
萌比男神i
萌比男神i 2020-12-21 03:35

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

相关标签:
2条回答
  • 2020-12-21 04:17

    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
          ]
    );
    
    0 讨论(0)
  • 2020-12-21 04:22

    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.

    0 讨论(0)
提交回复
热议问题