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