javascript - 与状态相关的每 5 秒运行一次方法
问题描述
我在组件中有从后端获取数据并检查状态的方法
就这个
getRecognitionById() {
this.loaderService.show(null, true);
this.vendorWebApiService
.createRecognition(this.executiveChangeId)
.pipe(take(1))
.subscribe((res) => {
this.vendorWebApiService
.getRecognition(res.taskRequestId, this.executiveChangeId)
.pipe(take(1))
.subscribe((recognitionResponse) => {
if (recognitionResponse.jobStatus === "completed") {
this.recognitionData = recognitionResponse;
this.getLatesFeedback();
}
if (recognitionResponse.jobStatus === "failed") {
alert();
} else {
}
});
});
}
在这部分我检查状态
this.vendorWebApiService
.getRecognition(res.taskRequestId, this.executiveChangeId)
.pipe(take(1))
.subscribe((recognitionResponse) => {
if (recognitionResponse.jobStatus === "completed") {
this.recognitionData = recognitionResponse;
this.getLatesFeedback();
}
if (recognitionResponse.jobStatus === "failed") {
alert();
} else {
}
});
但是如果状态是另一个然后完成或失败的问题,我需要每 5 秒重新运行一次这个逻辑,所以每 5 秒我需要检查一次状态,并且在 10 次尝试后,我需要显示警报。
我需要如何重写我的代码来实现这个逻辑?
解决方案
你可以用 rxjs 做到这一点
import { interval, Subject, Subscription } from 'rxjs';
refresher$: Observable<number>;
refreshSub: Subscription;
jobStatus: string = "init"
checkCount = 0
checkStatus() {
this.checkCount++
this.vendorWebApiService
.getRecognition(res.taskRequestId, this.executiveChangeId)
.pipe(take(1))
.subscribe((recognitionResponse) => {
jobStatus = recognitionResponse.jobStatus
this.recognitionData = recognitionResponse
});
}
getRecognitionById() {
this.loaderService.show(null, true);
this.checkStatus()
}
this.refresher$ = interval(5000); // every5 sec
this.refreshSub = this.refresher$.subscribe(() => {
this.checkStatus()
if (this.jobStatus === 'completed') {
this.getLatesFeedback();
}
if (this.jobStatus === 'failed') {
alert()
} else {
if (this.checkCount == 10) {
alert()
}
}
});
推荐阅读
- javascript - IntegrationError:paymentRequest() 的值无效:total.amount 应该是货币子单位中的正数。您指定:220.00000003
- python - 以自动方式创建具有某种形式的字符串的列表
- javascript - flexdashboard 行的图表部分中的选项卡
- regex - 正则表达式匹配和删除空格
- android - android.os.Build 从哪里获取它的值?(真的是 /system/build.prop 吗?)
- amazon-web-services - AWS MSK - Kafka 代理添加到 AWS 公共 DNS
- javascript - 当执行在同一`with`语句中声明的函数时,在`with`语句中声明的“找不到变量”
- android - java.lang.NullPointerException: Gson().fromJson(placeJson, Place::class.java) 不能为空
- ubuntu - 在 Ubuntu+Nginx+Tomcat 中部署 Geoserver 的问题
- docker - Dockerfile 中的条件环境定义