我尝试使用HttpClient为每个HTTP请求设置默认超时10秒。我有一个拦截器可以在标题中添加一些值,我已经读过这个设置超时,你必须使用'超时' RxJS运算符,如下所示:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { timeout } from 'rxjs/operators/timeout';
@Injectable()
export class APIInterceptor implements HttpInterceptor {
constructor() {
}
intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// NOTE: The following 'authToken' and 'user_id' values are obtained through a global service
const authReq = req.clone({
headers: new HttpHeaders ({
'Content-Type': 'application/json',
'X_TOKEN_AUTH': authToken,
'X_IDUSER': user_id
})
});
const API_TIMEOUT = 10000;
//console.log('HEADER: ', authReq)
return next.handle(authReq).timeout(API_TIMEOUT); // Set a timeout for the requests
}
}
在添加超时功能之前,一切正常,标头注入了身份验证令牌和用户ID。但是,现在我收到以下错误:
next.handle(...)。超时不是函数
我做错了吗?谢谢!
答案 0 :(得分:4)
如果你想使用&#34;补丁&#34;您需要从rxjs/add/operator/*
导入运算符的样式:
import 'rxjs/add/operator/timeout';
使用'rxjs/operators/timeout'
时使用pipe()
方法。