angularcachingangular-cache

Best approach to implement cache in Angular App


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?


Solution

  • I would personally go with as fine grained an approach as possible. So that'd be the service approach.

    I'd do this, because you most likely don't want to cache each and every request you make. If you do, I'll have to warn you, that it'll most likely introduce more problems than you think. Knowing when to clear a cache is often not very easy.

    So, rule of thumb: Cache only what really needs caching.