Angular 2 - 使用flatmap的同步http调用在返回空observable时不执行下一个调用

时间:2018-02-13 19:33:56

标签: angular http rxjs flatmap

我正以这种方式执行三次同步调用



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为空时,它不会执行下一次调用。有人可以建议这段代码出了什么问题。

由于

1 个答案:

答案 0 :(得分:1)

这是正确的,因为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尝试订阅时才会调用这些方法。

相关问题