1

在 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?

4

1 回答 1

0

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

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

所以,经验法则:只缓存真正需要缓存的东西。

于 2019-08-02T07:50:48.880 回答