如何检测间隔可观察开始请求的时间



我有我片段,它轮询服务器的付款状态。它每 5 秒执行一次,而状态未达到预期状态。

this.activatedRoute.params.subscribe((params: {orderId: string}) => {
    let subscription = interval(5000)
    .pipe(
        startWith(0),
        switchMap(() => this.paymentService.getStatusGuest(params.orderId)),
    )
    .subscribe((order: {status: string, amount?: number, message?: string}) => {
        if(order.status == 'error') {
            this.flashMessageService.set('error', order.message);
        } else {
            this.order = order;
        }
        if(order.status == 2 || order.status == 6 || order.status == -2)
        subscription.unsubscribe();
    });
});

现在,我想在执行轮询时显示预加载器。我应该如何检测间隔迭代开始?

一种方法是使用 tap() 运算符,它可用于执行副作用:

const subscription = this.activatedRoute.params
  .pipe(
    switchMap((params: {orderId: string}) => interval(5000)),
    tap(() => showPreloader()) // <-- PRELOADER SHOWN HERE
    startWith(0),
    switchMap(() => this.paymentService.getStatusGuest(params.orderId)),
  )
  .subscribe((order: {status: string, amount?: number, message?: string}) => {
      if(order.status == 'error') {
          this.flashMessageService.set('error', order.message);
      } else {
          this.order = order;
      }
      if(order.status == 2 || order.status == 6 || order.status == -2)
      subscription.unsubscribe();
  });

另一种不产生副作用的方法可能是在间隔上有两个订阅,所以像这样:

const intervalBeginning$ = this.activatedRoute.params.pipe(
  switchMap((params: {orderId: string}) => interval(5000))
);
const paymentStatusSubscripton = intervalBeginning$.pipe(
  startWith(0),
  switchMap(() => this.paymentService.getStatusGuest(params.orderId)),
)
.subscribe((order: {status: string, amount?: number, message?: string}) => {
    if(order.status == 'error') {
        this.flashMessageService.set('error', order.message);
    } else {
        this.order = order;
    }
    if(order.status == 2 || order.status == 6 || order.status == -2) {
      paymentStatusSubscripton.unsubscribe();
      showPreloaderSubscripton.unsubscribe();
    }
});
const showPreloaderSubscripton = intervalBeginning$.subscribe(() => {
    showPreloader(); // <-- PRELOADER SHOWN HERE
});

最新更新