首页 > 解决方案 > Angular RxJs:轮询 HTTP 请求,直到超时或来自服务器的肯定响应

问题描述

我是 RxJs 的新手。我需要轮询一个 http 请求并继续轮询,直到我得到一个肯定的响应或指定的时间已经过去(不想永远轮询)。

我正在使用 Angular 8 和 Typescript。这是我的代码:

this.httpClient.get('http://localhost:8060/api/portal/v1/payment/fetch/' + shopId + '/0/10').pipe(
          repeatWhen(obs => obs.pipe(delay(5000))),
          filter((data: ResponseModel<any>) => {
            console.log('Data:' + data);
            return data.status === 'success';
          }),
          take(1)
        ).subscribe(result => {
          console.log('Result: ' + result);
        });

上面的代码适用于来自服务器的正面响应,但如果没有正面响应,它会永远轮询,这不是预期的效果。如何在上述功能中添加超时?

标签: angularrxjsreactive-programming

解决方案


根据第一条评论中的建议,我调整了一些东西,最后得到了以下可行的方法

// Create an Observable that emits every 5 seconds
interval(5000).pipe(

          // Since the httpClient returns an Observable, wrap it with a switchMap
          switchMap(() => this.httpClient.get('http://localhost:8060/api/portal/v1/payment/fetch/' + shopId + '/0/10')),

          // Filter only the successful http responses
          filter((data: ResponseModel<any>) => {
            console.log('Data:' + JSON.stringify(data));
            return data.status === 'success';
          }),

          // Emit only the first value emitted by the source
          take(1),

          // Time out after 30 seconds
          timeout(30000),
        ).subscribe((result: ResponseModel<any>) => {

          console.log('Result: ' + JSON.stringify(result));

        }, error => {
          console.log('Error: ' + error);
        });

推荐阅读