如何在 Angular 9 中失败时重试订阅?

tom*_*ver 1 subscription observable rxjs angular angular9

上下文:使用 Angular 9。我正在尝试等待后端可用于接收请求。同时它不是,有一个进度条加载。

问题:当后端还不可用时,订阅立即失败并进入方法的(错误)回调函数,.subscribe()消息如下Http failure response for http://localhost:5555/api/info: 504 Gateway Timeout

我做了一些研究,我发现的示例修改了httpClient.get存在的服务类,以重试 x 次请求,但我不能这样做,因为 ts 服务是自动生成的。

我的第一个想法是使用 while() 循环和一个标志,因此每次执行 (error) 时,标志将为 false,然后重试订阅。但这会导致内存泄漏。

checkIfBackendAvailable() {
    var backendAvailable = false;
    while(!backendAvailable){
      let subscription = this.infoService.getInfo().subscribe(
      (info) => {
        if (info) {
            backendAvailable = true;
            this.progressBarValue = 100
            // do somethings
         }
       }
        ,
        (error) => {
          clearTimeout(this.infoTimeOut);
          this.showMessage("back-end not available");
          this.stopLoadingBar();
          //do somethings
        }
      );
    }

    this.infoTimeOut = setTimeout(() => {
      if (!backendAvailable) {
        subscription.unsubscribe()
        this.showMessage("error");
        this.stopLoadingBar();
      }
    }, 120000);
  }
Run Code Online (Sandbox Code Playgroud)

top*_*oon 5

只要您的服务函数返回,您仍然可以使用retryretryWhenobservable 运算符Observable

使用retry

this.infoService.getInfo()
  .pipe(
     retry(3), // you retry 3 times
     delay(1000) // each retry will start after 1 second,
  )
  .subscribe(res => {
     // success
  })
Run Code Online (Sandbox Code Playgroud)

使用retryWhen

this.infoService.getInfo()
  .pipe(
     retryWhen(errors => errors.pipe(
         // define conditions for retrying with some of observable operators
     )),
  )
  .subscribe(res => {
     // success
  })
Run Code Online (Sandbox Code Playgroud)