[英]Angular 2 promise/observable chain two events?
我想知道是否可以在角度2的以下用例中使用可觀察或承諾 :
有兩個異步上傳任務。 我想知道如何檢測這兩項任務都已完成。
我的上傳任務(在promise中實現,但如果需要可以很容易地更改為observable )是這樣的:
myService.upload('upload1').then(() => {
})
myService.upload('upload2').then(() => {
})
如何將這兩個事件鏈接在promise或observable中,以便我知道兩個任務都已完成? 謝謝
您可以將其中一個Combining Operators與observables一起使用。 例如, Observable.zip()
適用於promises ...
Observable.zip(
first,
second,
function (firstResolvedValue, secondResolvedValue) {
return firstResolvedValue && secondResolvedValue;
}
)
zip
接受可變數量的Observables或Promises作為參數,然后接受一個函數,該函數接受每個Observable發出的一個項目或由Promise作為輸入解析,並生成由生成的Observable發出的單個項目。
使用forkJoin ,相當於Angular 1.x的$ q.all(a和b是observables):
Rx.Observable.forkJoin([a,b]).subscribe(t=> {
var firstResult = t[0];
var secondResult = t[1];
});
關閉所有源流時執行complete
。
Rx.Observable.merge(
myService.upload('upload1'),
myService.upload('upload2').subscribe({complete: () => { ... });
如果要設置要等待的最大結果數
Rx.Observable.merge(
myService.upload('upload1'),
myService.upload('upload2')
.take(2)
.subscribe({complete: () => { ... });
您可以使用Promise.all,它返回一個新的Promise,它在參數數組中的所有promise都已解析時解析。
Promise.all([myService.upload('upload1'), myService.upload('upload2')]).then(() => {
// ...
});
注意,如果你的myService.upload方法返回了Promise而不是Promise,你可以這樣訪問返回值:
Promise.all([myService.upload('upload1'), myService.upload('upload2')])
.then((retValue1, retValue2) => {
// ...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.