在角结合的承诺2

在角结合的承诺2

本文介绍了在角结合的承诺2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在AngularJS 2诺言结合?
在1角,比如我会用 $ q.all 来的多个请求合并成一个单一的承诺。
是否有角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?

推荐答案

HTTP模块工作在观测量方面比承诺不同,但你既可以做链接和并行调用。

The http module works in terms of Observables which is different than promises, but you can do both chaining and parallel calls.

链接可以使用flatMap进行并行调用可以使用forkJoin进行处理。

Chaining can be done using flatMap and parallel calls can be handled using forkJoin.

例如:

//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:

您也可以拨打 toPromise()上的观测,并将其转换为常规承诺为好。

You can also call toPromise() on an Observable and convert it to a regular promise as well.

这篇关于在角结合的承诺2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:42