Angular 如何缓存特定时间的get请求?
如何使用Angular HttpInterceptor在一段时间内缓存get请求?我想在缓存进入服务器之前从缓存中获取响应 例如:Angular 如何缓存特定时间的get请求?,angular,typescript,angular-http-interceptors,Angular,Typescript,Angular Http Interceptors,如何使用Angular HttpInterceptor在一段时间内缓存get请求?我想在缓存进入服务器之前从缓存中获取响应 例如: 第一个请求从服务器获取数据 将响应缓存60秒 第二个请求从缓存中获取数据 如果第三个请求在60秒之后,则从服务器else缓存获取数据 @Injectable() export class JwtInterceptor implements HttpInterceptor { userDetails: any; constructor(public ro
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
userDetails: any;
constructor(public router: Router) { }
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (!request.url.includes('auth/login') && this.userDetails) {
// TODO: If no internet connectivity logout from the session
// For multi tenancy tenant ID is in auth token so no need to pass extra param just pass auth token
request = request.clone({
setHeaders: {
'x-access-token': CommonUtils.getCookie('token')
}
});
}
return next.handle(request).pipe(
map((event: HttpEvent<any>) => {
return event;
}),
catchError((error: HttpErrorResponse) => {
let data = {};
data = {
reason: error ? error : '',
status: error.status
};
return throwError(error);
})
);
}
}
@Injectable()
导出类JwtInterceptor实现HttpInterceptor{
用户详细信息:任何;
构造函数(公共路由器:路由器){}
拦截(
请求:HttpRequest,
下一步:HttpHandler
):可见{
if(!request.url.includes('auth/login')&&this.userDetails){
//TODO:如果没有internet连接,请从会话注销
//对于多租户,租户ID位于身份验证令牌中,因此无需传递额外参数,只需传递身份验证令牌即可
request=request.clone({
集合标题:{
'x-access-token':CommonUtils.getCookie('token')
}
});
}
返回next.handle(request.pipe)(
映射((事件:HttpEvent)=>{
返回事件;
}),
catchError((错误:HttpErrorResponse)=>{
让数据={};
数据={
原因:错误?错误:“”,
状态:error.status
};
返回投掷器(错误);
})
);
}
}
在这种情况下,您可以使用publishReplay缓存来自http调用的数据,并且可以提供第二个参数windowtime,以毫秒为单位,缓存在此时间之后将无效
分享您尝试过的内容会很有帮助。我刚刚创建了一个HttpInterceptor,用于为每个请求附加
x-access-token
头,因此我想知道是否有任何可能的方法通过使用HttpInterceptor来缓存请求。请直接分享拦截器的代码更新问题,请检查
httpCall.pipe(
publishReplay(1, 60000), // cache will be invalid after 60 seconds
refCount()
)