import { Injectable } from '@angular/core' ; import { HttpEvent , HttpRequest , HttpResponse , HttpInterceptor , HttpHandler } from '@angular/common/http' ; import { Observable , of } from 'rxjs' ; import { tap } from 'rxjs/operators' ; import { RequestCacheService } from './request-cache.service' ; /**
 * HTTP interceptor which quick caches previous api calls.
 */ @ Injectable ( ) export class APICachingInterceptor implements HttpInterceptor { constructor ( private cache ) { } param req param next intercept ( req , next ) { if ( ! isCacheable ( req ) ) { return next . handle ( req ) ; } const cachedResponse = this . cache . get ( req ) ; return cachedResponse ? of ( cachedResponse ) : this . sendRequest ( req , next , this . cache ) ; } param req param next param cache sendRequest ( req , next , cache ) { return next . handle ( req ) . pipe ( tap ( event => { if ( event instanceof HttpResponse ) { cache . put ( req , event ) ; } } ) ) ; } } /** Is this request cacheable? */ function isCacheable ( req ) { return req . method === 'GET' || req . method === 'HEAD' ; }