Best Online Tutorials

SQL Tutorial

Free SQL Tutorial

SQL Interview Questions

SQL Practice Questions

SQL Tips & Tricks

SQL Errors

SQL Books

Angular Tutorial

Free Angular Tutorial

Angular Interview Questions

Angular Practice Questions

Angular Tips & Tricks

Angular Errors

Angular Books

Node.js Tutorial

Free Node.js Tutorial

Node.js Interview Questions

Node.js Practice Questions

Node.js Tips & Tricks

Node.js Errors

Node.js Books

React.js Tutorial

Free React.js Tutorial

React.js Interview Questions

React.js Practice Questions

React.js Tips & Tricks

React.js Errors

React.js Books

SSIS Tutorial

Free SSIS Tutorial

SSIS Interview Questions

SSIS Practice Questions

SSIS Tips & Tricks

SSIS Errors

SSIS Books

SEO Tutorial

Free SEO Tutorial

SEO Interview Questions

SEO Practice Questions

SEO Tips & Tricks

SEO Errors

SEO Books

Javascript Tutorial

Free Javascript Tutorial

Javascript Interview Questions

Javascript Practice Questions

Javascript Tips & Tricks

Javascript Errors

Javascript Books

MongoDB Tutorial

Free MongoDB Tutorial

MongoDB Interview Questions

MongoDB Practice Questions

MongoDB Tips & Tricks

MongoDB Errors

MongoDB Books

Next.js Tutorial

Free Next.js Tutorial

Next.js Interview Questions

Next.js Practice Questions

Next.js Tips & Tricks

Next.js Errors

Next.js Books

Cache Interceptor in angular 4/5/6/7/8 and universal SSR 

Prashant Surya  |   Nov 28, 2019  |  Views: 1266

Description:

How to use Cache Interceptor in angular 4/5/6/7/8 using httpclient and with angular universal SSR?

What is cache interceptor?

A cache interceptor is a middleware handler to handle http request and response, to cache the response for the same request URL expiring till the mentioned or default duration.

Why to use?

If our website needs the same chunk of data from any hhtp request for the different pages or even at the same page, then we can cache the response at the first hit of http request and save it in the browser cache for the particular duration.

What are the benefits?

- It increases the data loading time of the website
- Users can see the data in a flash without buffering on page.
- Number of API calls is been reduced.


Create a cache.service.ts file 

import { Injectable } from '@angular/core';
import { HttpRequest, HttpResponse } from '@angular/common/http';
export interface RequestCacheEntry {
    url: string;
    response: HttpResponse<any>;
    lastRead: number;
}
export abstract class RequestCache {
    abstract get(req: HttpRequest<any>): HttpResponse<any> | undefined;
    abstract put(req: HttpRequest<any>, response: HttpResponse<any>): void
}

const maxAge = 5000000; // maximum cache age in ms
@Injectable()
export class RequestCacheWithMap implements RequestCache {
    cache = new Map<string, RequestCacheEntry>();
    constructor() { }
    get(req: HttpRequest<any>): HttpResponse<any> | undefined {
        const url = req.urlWithParams;
        const cached = this.cache.get(url);
        if (!cached) {
            return undefined;
        }
        const isExpired = cached.lastRead < (Date.now() - maxAge);
        const expired = isExpired ? 'expired ' : '';
       
        return isExpired ? undefined : cached.response;
    }
    put(req: HttpRequest<any>, response: HttpResponse<any>): void {
        const url = req.urlWithParams;      
        const entry = { url, response, lastRead: Date.now() };
        this.cache.set(url, entry);
        const expired = Date.now() - maxAge;
        this.cache.forEach(entry => {
            if (entry.lastRead < expired) {
                this.cache.delete(entry.url);
            }
        });
    }
}


Now create a cache.interceptor.ts file:

import { Injectable, Inject } from "@angular/core";
import { HttpEvent, HttpResponse, HttpErrorResponse } from "@angular/common/http";
import { Observable, of } from "rxjs";
import { tap } from 'rxjs/operators';
import {
    HttpRequest,
    HttpHandler,
    HttpInterceptor
} from "@angular/common/http";
import { RequestCacheWithMap } from "../requestCache.service";

@Injectable()
export class CacheInterceptor implements HttpInterceptor {
    constructor(@Inject(RequestCacheWithMap) private cache) { }
    intercept(req: HttpRequest<any>, next: HttpHandler) {
        const cachedResponse = this.cache.get(req);
        return cachedResponse ? of(cachedResponse) : this.sendRequest(req, next, this.cache);
    }
    sendRequest(
        req: HttpRequest<any>,
        next: HttpHandler,
        cache: RequestCacheWithMap): Observable<HttpEvent<any>> {
        const started = Date.now();
        return next.handle(req).pipe(
            tap(event => {
                if (event instanceof HttpResponse) {
                    cache.put(req, event);
                }
            }, (err: any) => {
                if (err instanceof HttpErrorResponse) {
                    const elapsed = Date.now() - started;
                    console.log(`Request for ${req.urlWithParams} failed after ${elapsed} ms.`);
                }
            })
        );
    }
}



Now in app.module.ts register these Interceptor:

import { HTTP_INTERCEPTORS} from '@angular/common/http';

providers: 
   { provide: HTTP_INTERCEPTORS, useClass: CacheInterceptor, multi: true }
],


The above three step is enough to set up the cache interceptor to your application, now every HTTP request will first check ,whether the response for this is  already in cache, if it exits then API doesn't been called and uses the saved response from the cache.

Comments:
Content Contributor
Prashant Surya

Prashant Surya

Software developer at Uniserve Data Technologies Pvt. Ltd.  |   Noida, Uttar Pradesh, India

I am a software developer, freelancer and trainer working on technologies likes. MEAN stack, MERN Stack, ASP.NET full stack, WebRTC, socket.io ,PWA, SQL, JavaScript, jQuery, HTML, CSS, SEO, responsive UI/UX designing... having 7 years of experience in development in multiple domains like, eCommerce, RTA, capital markets, education, real estate...


Read related articles

how to convert html to image in angular

Prashant Surya  |   Feb 12, 2020  |  Views: 3927

Copy to clipboard in angular

Prashant Surya  |   Jan 14, 2020  |  Views: 1349

How to use require() in angular typescript file

Prashant Surya  |   Jan 9, 2020  |  Views: 1873

Angular demo book - DritalConnect Suggestions

Prashant Surya  |   Dec 23, 2019  |  Views: 1244

Angular 8 reactive Form with validation

Prashant Surya  |   Dec 23, 2019  |  Views: 1492

What's new feature in Angular 9

Prashant Surya  |   Dec 18, 2019  |  Views: 1283

Home loan EMI calculator in Angular

Prashant Surya  |   Dec 17, 2019  |  Views: 3118

How to initialize an interface in typescript

Prashant Surya  |   Dec 13, 2019  |  Views: 2019

How to add google adsense in angular universal

Prashant Surya  |   Dec 2, 2019  |  Views: 2552

How to use localstorage in angular universal ssr

Prashant Surya  |   Nov 28, 2019  |  Views: 3646

How to manage multiple async calls in angular

Prashant Surya  |   Nov 27, 2019  |  Views: 1473

Angular tutorial - DritalConnect

Prashant Surya  |   Nov 20, 2019  |  Views: 1227

How to import a javascript file in angular

Pooja Goel  |   Nov 15, 2019  |  Views: 1435

Topics to learn in Angular | Angular Tutorial

Prashant Surya  |   Sep 25, 2019  |  Views: 1498

Difference between Angular and React js

Abhishek Roy  |   Sep 25, 2019  |  Views: 1429

Want to sell your software ?-

If you want to sell your readymade software to the genuine clients or businessman, list your software with details and demo links.

  • Sell ERP
  • Sell Website Clones
  • Sell App Clones
  • Sell Readymade Portals
  • Sell Readymade Websites
  • Sell Mobile Apps
  • Sell Window Apps

Clients will find it using our advanced search filter and will contact you directly.

No any charge for the product lsiting.

Do you own a Company ?+

Property.sale

Buy or Sell Commercial Property+

Are you a freelancer ?+

Looking for a job ?+

Are you a Service Provider ?+

Are you a blogger ?+

Do you own an IT Institute ?+



Property.sale