首页 > 解决方案 > 与状态相关的每 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 次尝试后,我需要显示警报。

我需要如何重写我的代码来实现这个逻辑?

标签: javascriptangulartypescript

解决方案


你可以用 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()
         }
      }

    });


推荐阅读