为什么我在http请求中拥有的超时运算符不会引发错误

时间:2019-06-25 08:44:24

标签: rxjs

当我定义的持续时间参数大于7000毫秒时,我定义的超时不会引发任何错误。奇怪的是,超时运算符在我的代码中从0到7000毫秒都能很好地工作

付款(计费):可观察{

const httpOptions = {
  headers: new HttpHeaders({
    //  'Access-Control-Allow-Origin':'*'
  }),
  params: new HttpParams()
    .append('timezone', billing.timezone)
    .append('mode', billing.mode)
    .append('responseFailURL', billing.responseFailURL)
    .append('responseSuccessURL', billing.responseSuccessURL)
    .append('hash', billing.hash)
    .append('txndatetime', billing.txndatetime)
    .append('chargetotal', billing.chargetotal.toString())
    .append('storename', billing.storename.toString())
    .append('currency', billing.currency.toString())
};
// Sending required payment infrmations to Authipay host url
return forkJoin(
  of(2), timer(2000).pipe(mergeMap(value => this.getPayementStatus(billing.txndatetime))).pipe( timeout(7500))
).pipe(
  map(
    ([articles, authorOfTheMonth]) => {
      console.log(authorOfTheMonth);
      return authorOfTheMonth;
    }
  )
).subscribe(
      resp => {
          this.router.navigate(['success'], { relativeTo: this.route });
        } else {
          form.setErrors({ paymentFailed: true });
          this.alertify.error(this.translate.instant('error.payment'));
        }
      },
      error => {
        if (error instanceof TimeoutError) {
          this.alertify.error(error.message);
        } else {
          this.alertify.error(this.translate.instant('error.payment'));
        }
      }
    );

1 个答案:

答案 0 :(得分:0)

timeout似乎按我的预期工作。

I wrote a test here,其中我的this.getPayementStatus(billing.txndatetime))函数替换为:

模拟的响应

const simulateResponseTime = (timeInMS)=> timer(timeInMS); // in milliseconds 

将在delayOfResponse毫秒内返回一个响应。使用此工具,我们可以测试当响应花费的时间超过超时阈值时会发生什么:

模拟参数

const timeoutThreshold = 7500; // in ms
const delayOfResponse = 200; //in ms

最后是

的简约版本

您的代码

forkJoin(of(2), timer(2000).pipe(
      mergeMap(value => simulateResponseTime(delayOfResponse))
    ).pipe(timeout(timeoutThreshold))
).pipe(
  ...
).subscribe(
      resp => {
          console.log('Success')
      },
      error => {
        console.log('Error message :', error.message)
        console.log('Error type :', error.name)
        console.log('Is a TimeoutError :', error.name === 'TimeoutError' )
      }
  );