4

我有一个简单的缓存拦截器,我希望我的缓存是不可变的。但不知何故,它不起作用。原始代码来自 HttpClient 文档https://angular.io/guide/http#intercepting-all-requests-or-responses

export class HttpCachingInterceptor implements HttpInterceptor {
private cache = new Map<string, HttpResponse<any>>();

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Before doing anything, it's important to only cache GET requests.
    // Skip this interceptor if the request method isn't GET.
    if (req.method !== 'GET') {
        return next.handle(req);
    }

    // First, check the cache to see if this request exists.
    const cachedResponse = this.cache.get(req.urlWithParams);
    if (cachedResponse && !req.headers.get('disable-cache')) {
        // A cached response exists. Serve it instead of forwarding
        // the request to the next handler.
        return Observable.of(cachedResponse.clone());
    }

    // No cached response exists. Go to the network, and cache
    // the response when it arrives.
    return next.handle(req).do(event => {
        // Remember, there may be other events besides just the response.
        if (event instanceof HttpResponse && !req.headers.get('disable-cache')) {
            // Update the cache.
            this.cache.set(req.urlWithParams, event.clone());
        }
    });
}

}

我有两个访问数据的组件。第一个组件在没有缓存的情况下检索完整数据(第一个请求)并通过以下方式修改数据

myHttpService.getCategories().map((root) => {
        root.categories.splice(0, 1);

第二个组件使用相同的服务 myHttpService 但响应是从缓存中提供的,并且数据是变异的。我知道在这种情况下我可以使用 slice,但我的缓存应该是不可变的,如果不使用其他库,我该如何实现呢?

4

0 回答 0