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