我在组件中有方法从后端获取数据并检查状态
在这里
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()
}
}
});
你可以这样做:
-
定义计数器变量
-
定义一个带有5000ms定时器的间隔,并将其引用到一个变量
-
清除成功时间间隔。
-
故障时的重新运行间隔和
counter < 10
的计数器。
let counter = 0;
let interval = setInterval(() => {
// ajax().next(() => {
// clearInterval(interval);
// }).catch(() => {
// if (counter >= 10) {
// clearInterval(interval);
// } else {
// counter++;
// }
// })
}, 5000);
- 不要忘记在
ngOnDestroy
中清除您的间隔,以防止您的应用程序在某些情况下崩溃。
对于可观察对象,您可以尝试这样做
getRecognitionById() {
// this.loaderService.show(null, true);
const ATTEMPT_COUNT = 10;
const DELAY = 5000;
this.vendorWebApiService
.createRecognition(this.executiveChangeId)
.pipe(take(1),
mergeMap((res) => (
this.vendorWebApiService
.getRecognition(res.taskRequestId, this.executiveChangeId)
.pipe(take(1),
))), map((recognitionResponse: any) => {
if (recognitionResponse.jobStatus === "completed") {
this.recognitionData = recognitionResponse;
this.getLatesFeedback();
}
if (recognitionResponse.jobStatus === "failed") {
alert();
} else {
throw { error: 'failed' };
}
}), retryWhen(errors => errors.pipe(
scan((errorCount, err: any) => {
if (err.error === 'failed' || errorCount >= ATTEMPT_COUNT) {
// add code for alert after 10 retries
}
return errorCount + 1;
}, 0),
delay(DELAY),
)));
}