angular - 第一次请求时出现角度缓存拦截器问题
问题描述
Angular6 缓存拦截器工作正常,但页面上的第一个请求存在问题(例如,当我从同一页面/视图上的几个管道/组件发送词汇请求时)。
我在我的代码中尝试了类似下面的内容:
intercept(req: HttpRequest<any>, next: HttpHandler) {
const cachedResponse = this.cache.get(req.url);
return cachedResponse ? of(cachedResponse) : this.sendRequest(req, next);
}
sendRequest(
req: HttpRequest<any>,
next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
tap(event => {
if (event instanceof HttpResponse && this.isCachable(req.url)) {
this.cache.put(req.url, event);
}
})
);
}
现在,当我对一个 URL 有六个请求时(例如在网络中我有六个时间 /getUsers url)。我认为拦截器首先保存我的数据然后使用它 - 但这仅在第一次视图加载后发生。
异步有问题吗?缓存不能准时?
解决方案
我做了这样的事情:
async sendRequest(
req: HttpRequest<any>,
next: HttpHandler) {
try {
return await next.handle(req).pipe(
tap(event => {
if (event instanceof HttpResponse && this.isCachable(req.url)) {
const a = this.cache.put(req.url, event);
a.then(_.noop);
}
})
);
} catch (error) {
return next.handle(req);
}
}
但现在我遇到了错误
'CacheInterceptor' 类型中的属性 'intercept' 不能分配给基类型 'HttpInterceptor' 中的相同属性。
在拦截之前放置异步我有同样的错误
此外,我在这里检查了等待:
return cachedResponse ? of(cachedResponse) : this.sendRequest(req, next);
仍然没有:
await 表达式只允许在异步函数中使用
推荐阅读
- typescript - 打字稿,带有长度信息的类型
- spring-cloud-contract - 如何在不应用正文的情况下仅在存根处使用匹配器?
- node.js - npm install 显示错误,找不到 git
- c++ - 没有类减法运算符重载但仍然有效
- python - python多线程服务器从浏览器收到两个请求
- java - java.lang.IllegalArgumentException:没有找到类型返回值的转换器:类 java.util.ArrayList
- java - 从没有window.open的rest api下载文件
- import - 错误:找不到模块“nativescript-zxing”
- webpack - 如何在 Svelte 编译器中使用 Rollup 或 Webpack 预处理组件 CSS 和全局样式?
- swift - Swift - 调度队列和 U/I 串行运行