31 lines
1.0 KiB
TypeScript
31 lines
1.0 KiB
TypeScript
import { Injectable } from '@angular/core';
|
|
import { HttpEvent, HttpRequest, HttpResponse, HttpInterceptor, HttpHandler } from '@angular/common/http';
|
|
|
|
// import { Observable } from 'rxjs/Observable';
|
|
// import 'rxjs/add/observable/of';
|
|
import { tap } from 'rxjs/operators';
|
|
import { Observable, of } from 'rxjs';
|
|
|
|
import { RequestCache } from '../services/request-cache.service';
|
|
|
|
@Injectable()
|
|
export class CachingInterceptor implements HttpInterceptor {
|
|
constructor(private cache: RequestCache) { }
|
|
|
|
intercept(req: HttpRequest<any>, next: HttpHandler) {
|
|
const cachedResponse = this.cache.get(req);
|
|
return cachedResponse ? of(cachedResponse) : this.sendRequest(req, next);
|
|
}
|
|
|
|
sendRequest(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
|
return next.handle(req)
|
|
.pipe(
|
|
tap(event => {
|
|
if (event instanceof HttpResponse) {
|
|
this.cache.put(req, event);
|
|
}
|
|
})
|
|
);
|
|
}
|
|
}
|