我有我的代码段,用于查询用户的付款状态的轮询服务器。它每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();
});
});
现在,我想在执行轮询时显示预加载器。我应该如何检测间隔迭代的开始?
答案 0 :(得分:3)
一种实现方法是使用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
});