1

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?

Bhagwat Tupe
  • 1,905
  • 1
  • 13
  • 28
Kacper O
  • 13
  • 4
  • Actually I would use neither. How much data do you want to cache? What data do you want to cache? How often do you access this cache? It is likely that Redux or Subjects would be more appropriate. – MoxxiManagarm Aug 02 '19 at 07:37
  • I have a GET which take ~500ms. The response is changing after each 30min, so there is no logical explanation why should i dont use cache here, during this period. This is my own app so I just want to learn how can i use cache properly. – Kacper O Aug 02 '19 at 07:43

1 Answers1

0

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.

Thor Jacobsen
  • 8,621
  • 2
  • 27
  • 26