Skip to content

Instantly share code, notes, and snippets.

@kudchikarsk
Last active April 21, 2019 05:55
Show Gist options
  • Select an option

  • Save kudchikarsk/31fcff60baefec4ea653f77e517bb22d to your computer and use it in GitHub Desktop.

Select an option

Save kudchikarsk/31fcff60baefec4ea653f77e517bb22d to your computer and use it in GitHub Desktop.
Cache interceptor in Angular using a cache service
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { HttpCacheService } from 'app/services/http-cache.service'; // https://gist.github.com/kudchikarsk/f2f8754eca3cf86db3fbbc833c330e55
@Injectable()
export class CacheInterceptor implements HttpInterceptor {
constructor(private cacheService: HttpCacheService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// pass along non-cacheable requests and invalidate cache
if(req.method !== 'GET') {
console.log(`Invalidating cache: ${req.method} ${req.url}`);
this.cacheService.invalidateCache();
return next.handle(req);
}
// attempt to retrieve a cached response
const cachedResponse: HttpResponse<any> = this.cacheService.get(req.url);
// return cached response
if (cachedResponse) {
console.log(`Returning a cached response: ${cachedResponse.url}`);
console.log(cachedResponse);
return of(cachedResponse);
}
// send request to server and add response to cache
return next.handle(req)
.pipe(
tap(event => {
if (event instanceof HttpResponse) {
console.log(`Adding item to cache: ${req.url}`);
this.cacheService.put(req.url, event);
}
})
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment