How to cache HTTP requests in Angular

0 votes
Can you tell me How to cache HTTP requests in Angular
6 days ago in Node-js by Ashutosh
• 24,010 points
51 views

1 answer to this question.

0 votes

In Angular, you can cache HTTP requests using RxJS operators and Interceptor.

Use an HTTP Interceptor

1. Create an Interceptor:

import { Injectable } from '@angular/core';

import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';

import { Observable, of } from 'rxjs';

import { tap, shareReplay } from 'rxjs/operators';

@Injectable()

export class CacheInterceptor implements HttpInterceptor {

  private cache = new Map<string, any>();

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

    if (req.method !== 'GET') {

      return next.handle(req); 

    }

    const cachedResponse = this.cache.get(req.url);

    if (cachedResponse) {

      return of(cachedResponse); 

    }

    return next.handle(req).pipe(

      tap(event => this.cache.set(req.url, event)),

      shareReplay(1) 

    );

  }

}

2.Register the Interceptor in `app.module.ts`:

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

providers: [

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

]

answered 6 days ago by anonymous

Related Questions In Node-js

0 votes
0 answers

How to handle HTTP GET requests in Angular using HttpClient?

Can you explain with the help of ...READ MORE

Mar 19 in Node-js by Ashutosh
• 24,010 points
38 views
0 votes
0 answers

How to handle HTTP request timeouts using RxJS operators in Angular?

Can you tell me How to handle ...READ MORE

6 days ago in Node-js by Ashutosh
• 24,010 points
37 views
0 votes
1 answer

How to use switchMap to handle dependent HTTP requests in RxJS?

Using switchMap for Dependent HTTP Requests in ...READ MORE

answered 6 days ago in Node-js by anonymous
51 views
+1 vote
1 answer

How to make external HTTP requests with Node.js ?

Hello @kartik, Use this: var http = require('http'); var options ...READ MORE

answered Oct 12, 2020 in Node-js by Niroj
• 82,840 points
1,964 views
0 votes
1 answer
0 votes
0 answers
0 votes
0 answers

How to monitor progress of HTTP Get Request

With the help of code can you ...READ MORE

6 days ago in Node-js by Ashutosh
• 24,010 points
26 views
0 votes
0 answers

How to call another HTTP request after forkJoin is completed (RxJS)?

With the help of proper programming can ...READ MORE

6 days ago in Node-js by Ashutosh
• 24,010 points
24 views
0 votes
1 answer
0 votes
1 answer

How to Handle Jest Unit Testing for 'ɵcmp' in a React-in-Angular Hybrid App?

Encountering the 'ɵcmp' property error during Jest ...READ MORE

answered Dec 23, 2024 in Node-js by Navya
114 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP