Angular 2 - 当返回一个空的可观察对象时,使用平面图的同步 http 调用不执行下一个调用

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 尝试订阅时被调用。