首页 > 解决方案 > 无限调用API方法(检查状态)

问题描述

有没有一种方法可以无限地调用Angular(或Ionic)中的函数而不会停止?

我正在模拟付款过程。流程如下:我使用 POST 方法发送付款,API 将我发送到提供付款状态的 URL。

在我这边,我必须等到我从后面得到这个付款状态。所以我有一个检查状态的方法。我想无限地调用这个方法,直到我得到状态。

我看到 Angular 中有“ng-repeat”,但我没有处理 HTML 模板,它在我的 TypeScript 文件中。

这是我的代码:

ionViewWillEnter(){
    this.paymentService.postPayment(id, total, currency).subscribe({
      next: () => {
        
// Here I want to check status undefinitely
    this.paymentService.checkStatus().subscribe({
      next: (result) => {
  // WHEN RESULT IS SUCCESS,  DO REDIRECTION...
      this.router.navigate(['...']);
      },
      error: () => {
            
      },
    });
    }

}

标签: angularhttpionic-framework

解决方案


您可能想了解更多关于 RxJs 和 HTTP 请求的信息。

主要思想是使用 Angular 创建一个可观察的 http 请求HttpClient,然后.pipe()使用 RxJs 运算符使其在失败时重试。

这是 Angular 文档中的一个示例:

getConfig() {
  return this.http.get<Config>(this.configUrl)
    .pipe(
      retry(3), // retry a failed request up to 3 times
      catchError(this.handleError) // then handle the error
    );
}

我猜你必须修改它并应用一些运算符来告诉 RxJs 你如何为你的请求定义失败/成功,但没有更多细节就不容易说。

重试失败的请求| RxJs 运算符


推荐阅读