How to create caching service by using interceptor to cache http request, to save in bandwidth  and speed up our up?

Well, here is how!


In order to cache requests on Angular side, we will create interceptor caching service where we will cache all GET request (except couple of exceptions) and when user try to load that same resource again it will be served from the cache.


So let's first create our  cache.service.ts

                    import { Injectable } from '@angular/core';
import {HttpResponse} from "@angular/common/http";
import {Globals} from "../globals";

  providedIn: 'root'
export class CacheService {

    private globals: Globals,
  ) { }

  private cache:any = {};

  doNotCache = [
    // ....

  cacheResponse(responseURL: string, response: HttpResponse<any>):void{
    this.cache[responseURL] = response;

  getCachedResponse(requestURL: string): HttpResponse<any> | null{
    return this.cache[requestURL];

  deleteCachedResponse(requestURL: string){
    this.cache[requestURL] = null;
    this.cache = {};
    return this.cache;

    return encodeURIComponent(url);

    return decodeURIComponent(url);


    let url = this.encodeURL(path);

    for (let i = 0; i < this.doNotCache.length;i++){


        return true;



    return false;





Now in  our intercept-request.service.ts use this caching service:

                    intercept(request: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {

    // set caching request
      if(request.method !== 'GET'){
         // delete cache on any other request type  - if you want

          // check do we have this request cached and return it
          const cachedResponse = this.cacheService.getCachedResponse(this.cacheService.encodeURL(request.url));
          if (cachedResponse) {
            console.log("serving from cache");
            return of(cachedResponse);

    // end of caching request

// check response
    return next.handle(request)
        tap(event => {
          if (event instanceof HttpResponse) {
            // should we cache reqeust?
            if(request.method === 'GET' &&
              !this.cacheService.includesDoNotCache(request.url) &&

              this.cacheService.cacheResponse(this.cacheService.encodeURL(request.url), event);





We can also delete some urls from cache by calling  CacheService.deleteCachedResponse(url) - this can be useful when user change some content in that case we can delete that URL. Another way to delete is when user log out, then we can call CacheService.clearCache();