我有一个简单的缓存拦截器,我希望我的缓存是不可变的。但不知怎的,它不起作用。原始代码来自HttpClient doc 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,但响应是从缓存提供的,数据是变异的。我知道在这种情况下我可以使用切片但是我的缓存应该是不可变的如何在不使用其他库的情况下实现这一点?