首页 > 解决方案 > 第一次请求时出现角度缓存拦截器问题

问题描述

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)。我认为拦截器首先保存我的数据然后使用它 - 但这仅在第一次视图加载后发生。

异步有问题吗?缓存不能准时?

标签: angular

解决方案


我做了这样的事情:

    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 表达式只允许在异步函数中使用


推荐阅读