在 Angular 应用程序中实现缓存的最佳方法

Best approach to implement cache in Angular App

在 angular 应用程序中实现缓存的最佳方法是什么?

我发现了两种不同的方式: - 第一个是创建一个像 CacheService 这样的简单服务,并在那里做必要的逻辑。 - 第二个选项是创建一个 HttpInterceptor 并捕获每个请求和 return 缓存响应(如果存在)。

// 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 {}
}


是使用 HttpInterceptor 的好方法还是我应该只使用 CacheService 而不使用 CachingInterceptorService?

我个人会尽可能采用细粒度的方法。这就是服务方式。

我会这样做,因为您很可能不想缓存您发出的每一个请求。如果你这样做,我必须警告你,它很可能会带来比你想象的更多的问题。知道何时清除缓存通常不是很容易。

因此,经验法则:仅缓存真正需要缓存的内容。