Tengo un método en el componente que obtiene datos del back-end y verifica los estados
Aquí es
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 { } }); }); }En esta parte compruebo el estado
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 { } });Pero el problema es que si el estado es otro, luego está completo o fallado, necesito volver a ejecutar esta lógica cada 5 segundos, por lo que cada 5 segundos necesito verificar el estado y después de 10 intentos, necesito mostrar una alerta.
¿Cómo necesito reescribir mi código para lograr esta lógica?
Puedes hacer esto con 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() } } });Puedes lograrlo de esta manera:
Defina una variable de contador.
Defina un intervalo con un temporizador de 5000ms y haga referencia a una variable.
Intervalo claro en el éxito.
Vuelva a ejecutar el intervalo en caso de falla y un contador de counter < 10 .
let counter = 0; let interval = setInterval(() => { // ajax().next(() => { // clearInterval(interval); // }).catch(() => { // if (counter >= 10) { // clearInterval(interval); // } else { // counter++; // } // }) }, 5000);ngOnDestroy para evitar que su aplicación se bloquee en algunos escenarios.Con observables podrías intentar algo como esto
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), ))); }