首页 > 解决方案 > 如何检测间隔可观察开始请求的时间?

问题描述

我有我的片段,它轮询服务器以获取用户的付款状态。它每 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();
    });
});

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

标签: angularrxjs

解决方案


一种方法是使用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
});

推荐阅读