Last active
April 21, 2019 05:55
-
-
Save kudchikarsk/31fcff60baefec4ea653f77e517bb22d to your computer and use it in GitHub Desktop.
Cache interceptor in Angular using a cache service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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