2 changed files with 42 additions and 2 deletions
@ -1,13 +1,20 @@ |
|||||
import { ApplicationConfig } from '@angular/core'; |
import { ApplicationConfig } from '@angular/core'; |
||||
import { provideRouter } from '@angular/router'; |
import { provideRouter } from '@angular/router'; |
||||
import { provideHttpClient } from '@angular/common/http'; |
import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptors, withInterceptorsFromDi } from '@angular/common/http'; |
||||
|
|
||||
import { routes } from './app.routes'; |
import { routes } from './app.routes'; |
||||
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async'; |
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async'; |
||||
|
import { CacheInterceptor } from './interceptors/httpCache.interceptor'; |
||||
|
|
||||
export const appConfig: ApplicationConfig = { |
export const appConfig: ApplicationConfig = { |
||||
providers: [ |
providers: [ |
||||
provideRouter(routes), |
provideRouter(routes), |
||||
provideHttpClient(), provideAnimationsAsync() |
provideHttpClient(withInterceptorsFromDi()), |
||||
|
provideAnimationsAsync(), |
||||
|
{ |
||||
|
provide: HTTP_INTERCEPTORS, |
||||
|
useClass: CacheInterceptor, |
||||
|
multi: true |
||||
|
} |
||||
] |
] |
||||
}; |
}; |
||||
|
|||||
@ -0,0 +1,33 @@ |
|||||
|
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from "@angular/common/http"; |
||||
|
import { Injectable } from "@angular/core"; |
||||
|
import { Observable, of, tap } from "rxjs"; |
||||
|
|
||||
|
@Injectable() |
||||
|
export class CacheInterceptor implements HttpInterceptor { |
||||
|
private cache = new Map<string, any>(); |
||||
|
|
||||
|
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { |
||||
|
// Only cache GET requests
|
||||
|
if (req.method !== 'GET') { |
||||
|
return next.handle(req); |
||||
|
} |
||||
|
|
||||
|
const cachedResponse = this.cache.get(req.urlWithParams); |
||||
|
if (cachedResponse) { |
||||
|
// Serve from cache
|
||||
|
console.log("cache hit") |
||||
|
return of(cachedResponse); |
||||
|
} |
||||
|
|
||||
|
console.log("cache miss") |
||||
|
|
||||
|
return next.handle(req).pipe( |
||||
|
tap(event => { |
||||
|
if (event instanceof HttpResponse) { |
||||
|
// Cache the new response
|
||||
|
this.cache.set(req.urlWithParams, event); |
||||
|
} |
||||
|
}) |
||||
|
); |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue