3
有什么方法可以将AngularJS 2中的承诺结合起来?例如,在角1中,我将使用$q.all
将多个请求组合成单个承诺。 有没有Angular 2的等价物?结合Angular 2中的承诺
有什么方法可以将AngularJS 2中的承诺结合起来?例如,在角1中,我将使用$q.all
将多个请求组合成单个承诺。 有没有Angular 2的等价物?结合Angular 2中的承诺
http模块的工作方式不同于承诺的Observable,但您可以同时进行链接和并行调用。
可以使用flatMap完成链接,并且可以使用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]});
你可以找到更多的细节,在这里演示:
http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http
您也可以拨打上可观察到的toPromise()
并将其转换为常规承诺为好。
$ q.all没有链接承诺,但将它们结合在一起解决,或者当第一个拒绝时拒绝。这里承诺的顺序没有意义。你有Promise.all来做同样的工作。 –
我的错误;我更新了标题和问题! – user2884505