What is the best approach to implement cache in angular App?
I found two different way: - First one is to create a simple service like CacheService and do there necessary logic. - Second option is to create a HttpInterceptor and catch each request and return cached response if existing.
// CachingInterceptorService
@Injectable()
export class CachingInterceptorService implements HttpInterceptor {
constructor(private cacheService: CacheService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler) {
const cachedData = this.cacheService.getCache(req);
if (cachedData !== undefined) {
return of(cachedData);
} else {
return next.handle(req);
}
}
}
// otherService with http
getList(): Observable<any> {
return this.http.get(url, option)
.pipe(
tap(value => {
this.cacheService.setCache(key, value);
return value;
})
);
}
//CacheService
@Injectable({providedIn: 'root'})
export class CacheService {
cache = new Map();
constructor() {}
getCache(req: HttpRequest<any>): any | undefined {}
setCache(key: string, data: any): void {}
}
Is the good way to use HttpInterceptor or should I just use CacheService without CachingInterceptorService?