angular - 如何检测间隔可观察开始请求的时间?
问题描述
我有我的片段,它轮询服务器以获取用户的付款状态。它每 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
});
推荐阅读
- javascript - Django响应将json设置为cookie
- java - 如何在Nodejs(如Java)中将字符串转换为字节数组
- python - 如何反转标签的 One-Hot Encoding 以评估 ML/DL 模型?
- flutter - 如何在 Flutter 中通过卡片点击打开另一个页面
- javascript - 是否有更新实时烛台图表的示例?
- nginx - 在 Nginx 中为某些 IP 禁用缓存控制
- javascript - 如何使用 parsimmon.js 解析 jsDoc 注释?
- c++ - 当调用函数中捕获到异常时,如何确保在函数内删除数组?
- python - DJANGO REST FRAMEWORK 中的注册问题
- spring - 在哪个场景中,我们在 applicationContext 上调用 refresh(),start() 和 refresh() 方法有什么区别?