Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

154
Vistas
Ejecutar método cada 5 segundos relacionado con el estado

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?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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() } } });
over 4 years ago · Santiago Trujillo Denunciar

0

Puedes lograrlo de esta manera:

  1. Defina una variable de contador.

  2. Defina un intervalo con un temporizador de 5000ms y haga referencia a una variable.

  3. Intervalo claro en el éxito.

  4. 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);
  • NO olvide borrar su intervalo en ngOnDestroy para evitar que su aplicación se bloquee en algunos escenarios.
over 4 years ago · Santiago Trujillo Denunciar

0

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), ))); }
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda