【发布时间】: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