[英]Angular 2 - Synchronous http calls using flatmap is not performing the next calls when an empty observable is returned
我正在以這種方式執行三個同步調用
this.deletePreallocations() .flatMap(() => { return this.postPreallocations(); }) .flatMap(() => { return this.postPayment(); }) .takeWhile(() => this.isAlive) .subscribe( () => { }, err => { console.log(err); });
而每次調用都是這樣的
deletePreallocations() { if (this.preAllocationsDeleteIds.length > 0) { let self = this; let prealloctionsDeleteIDs = this.preAllocationsDeleteIds.filter(function (item, index) { return self.preAllocationsDeleteIds.indexOf(item) === index; }); return this.paymentsService.deletePreallocations(this.payment.ID, prealloctionsDeleteIDs); } return Observable.empty(); } postPreallocations() { if (this.preallocationupdatedValues.length > 0) { return this.paymentsService.postPreallocationsCollection(this.payment.ID, this.preallocationupdatedValues); } return Observable.empty(); } postPayment() { return this.paymentsService.post(this.payment); }
所以問題是當返回的 observable 為空時,它不會執行下一次調用。 有人可以建議此代碼有什么問題。
謝謝
這是正確的,因為flatMap
僅適用於next
通知,而Observable.empty()
僅發送complete
通知而沒有其他任何內容。
所以你可以做的不是依賴next
通知,而是等待前一個 Observable 完成:
this.deletePreallocations()
.concat(Observable.defer(() => this.postPreallocations()))
.concat(Observable.defer(() => this.postPayment()))
.takeWhile(() => this.isAlive)
.subscribe(
() => { },
err => {
console.log(err);
}
);
我正在使用Observable.defer
,它僅在您訂閱它時調用它的回調。 由於在this.postPreallocations()
和this.postPayment()
你有一些依賴於內部狀態的邏輯,這應該保證只有在concat
嘗試訂閱時才會調用這些方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.