结合Angular 2中的承诺

前端之家收集整理的这篇文章主要介绍了结合Angular 2中的承诺前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法在AngularJS 2中结合承诺?
例如,在Angular 1中,我将使用$q.all将多个请求合并为一个promise.
Angular 2有等价物吗?
http模块的工作方式是Observables,它与promises不同,但你可以同时进行链接和并行调用.

链接可以使用flatMap完成,并行调用可以使用forkJoin处理.

例子:

  1. //dependent calls (chaining)
  2. this.http.get('./customer.json').map((res: Response) => {
  3. this.customer = res.json();
  4. return this.customer;
  5. })
  6. .flatMap((customer) => this.http.get(customer.contractUrl)).map((res: Response) => res.json())
  7. .subscribe(res => this.contract = res);
  8.  
  9. //parallel
  10. import {Observable} from 'rxjs/Observable';
  11. Observable.forkJoin(
  12. this.http.get('./friends.json').map((res: Response) => res.json()),this.http.get('./customer.json').map((res: Response) => res.json())
  13. ).subscribe(res => this.combined = {friends:res[0].friends,customer:res[1]});

您可以在此处找到更多详细信息和演示:

http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http

您还可以在Observable上调用toPromise()并将其转换为常规promise.

猜你在找的Angularjs相关文章