默认和特定请求超时 [英] Default and specific request timeout

查看:130
本文介绍了默认和特定请求超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,最好将默认超时时间(例如30秒)应用于所有请求,并且可以针对特定的更长的请求(例如600s)进行覆盖。

Usually it's desirable to have default timeout (e.g. 30s) that will be applied to all requests and can be overridden for particular longer requests (e.g. 600s).

据我所知,没有很好的方法在 Http 服务中指定默认超时。

There's no good way to specify default timeout in Http service, to my knowledge.

HttpClient 服务中如何解决此问题?

What is the way to approach this in HttpClient service? How to define a default timeout for all outgoing requests, that can be overriden for specific ones?

推荐答案

如何为所有传出的请求定义默认超时,可以为特定请求覆盖? code> HttpClientModule 类,拦截器与各个请求进行通信的唯一预期方式是 params headers 对象。

It appears that without extending HttpClientModule classes, the only expected ways for interceptors to communicate with respective requests are params and headers objects.

由于超时值是标量,因此可以安全地将其作为自定义标头提供给拦截器,在此可以确定是否为默认值或应通过RxJS timeout 运算符应用的特定超时:

Since timeout value is scalar, it can be safely provided as a custom header to the interceptor, where it can be decided if it's default or specific timeout that should be applied via RxJS timeout operator:

import { Inject, Injectable, InjectionToken } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { timeout } from 'rxjs/operators';

export const DEFAULT_TIMEOUT = new InjectionToken<number>('defaultTimeout');

@Injectable()
export class TimeoutInterceptor implements HttpInterceptor {
  constructor(@Inject(DEFAULT_TIMEOUT) protected defaultTimeout: number) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const timeoutValue = req.headers.get('timeout') || this.defaultTimeout;
    const timeoutValueNumeric = Number(timeoutValue);

    return next.handle(req).pipe(timeout(timeoutValueNumeric));
  }
}

可以在您的应用模块中进行配置,例如:

This can be configured in your app module like:

providers: [
  [{ provide: HTTP_INTERCEPTORS, useClass: TimeoutInterceptor, multi: true }],
  [{ provide: DEFAULT_TIMEOUT, useValue: 30000 }]
],

然后使用自定义的超时标头

http.get('/your/url/here', { headers: new HttpHeaders({ timeout: `${20000}` }) });

由于标头应为字符串,因此超时值应首先转换为字符串。

Since headers are supposed to be strings, the timeout value should be converted to a string first.

这里是一个演示

信用归@RahulSingh和@ Jota.Toledo建议使用在超时时使用拦截器的想法。

Credits go to @RahulSingh and @Jota.Toledo for suggesting the idea of using interceptors with timeout.

这篇关于默认和特定请求超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆