【问题标题】:Best approach to implement cache in Angular App在 Angular App 中实现缓存的最佳方法
【发布时间】:2019-12-10 19:17:35
【问题描述】:

在 Angular App 中实现缓存的最佳方法是什么?

我发现了两种不同的方式: - 第一个是创建一个简单的服务,如 CacheService 并执行必要的逻辑。 - 第二种选择是创建一个 HttpInterceptor 并捕获每个请求并返回缓存的响应(如果存在)。

// 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 的好方法还是应该只使用没有 CachingInterceptorService 的 CacheService?

【问题讨论】:

  • 其实我都不会用。您要缓存多少数据?你想缓存什么数据?您多久访问一次此缓存? Redux 或 Subjects 可能更合适。
  • 我有一个 GET 大约需要 500 毫秒。响应在每 30 分钟后发生变化,因此没有合乎逻辑的解释为什么我不应该在此期间使用缓存。这是我自己的应用程序,所以我只想了解如何正确使用缓存。

标签: angular caching angular-cache


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2011-09-17
    • 2018-05-19
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 2018-03-16
    相关资源
    最近更新 更多