通常,需要有默认超时时间(例如30秒),该时间将应用于所有请求,并且可以覆盖特定的longer个请求(例如600秒).
据我所知,在Http
服务中没有指定默认超时的好方法.
如何在HttpClient
服务中实现这一点?如何为所有发出的请求定义一个默认超时,该超时可以被特定请求覆盖?
通常,需要有默认超时时间(例如30秒),该时间将应用于所有请求,并且可以覆盖特定的longer个请求(例如600秒).
据我所知,在Http
服务中没有指定默认超时的好方法.
如何在HttpClient
服务中实现这一点?如何为所有发出的请求定义一个默认超时,该超时可以被特定请求覆盖?
似乎在不扩展HttpClientModule
个类的情况下,拦截器与相应请求通信的唯一预期方式是params
和headers
个对象.
由于超时值是标量值,因此可以安全地将其作为自定义头提供给拦截器,在拦截器中可以确定它是默认超时还是特定超时,应该通过RxJS timeout
运算符应用:
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));
}
}
这可以在您的应用程序模块中进行配置,如下所示:
providers: [
[{ provide: HTTP_INTERCEPTORS, useClass: TimeoutInterceptor, multi: true }],
[{ provide: DEFAULT_TIMEOUT, useValue: 30000 }]
],
然后使用定制的timeout
报头完成请求
http.get('/your/url/here', { headers: new HttpHeaders({ timeout: `${20000}` }) });
由于头应该是字符串,所以应该首先将超时值转换为字符串.
这是a demo美元.
学分归@RahulSingh和@Jota.托莱多建议使用timeout
个拦截弹.