如何将多个StoreService_getItemById_缓存合并为LocalStorage单数组存储
解决方案:合并LocalStorage缓存为单一数组项
核心修改思路
要实现将所有StoreService_getItemById_相关数据合并到单个缓存项,需要从统一缓存Key、数组缓存的读写逻辑两方面调整代码:
- 废弃原有的带
id的动态Key,改用固定前缀+员工ID的统一Key - 重写缓存读写逻辑,支持在数组中查找、添加或更新指定ID的项
具体代码修改
1. 调整getItemById方法(生成统一缓存Key)
getItemById(id) { // 用统一Key:去掉原Key中的id部分,同一员工的所有item共享一个缓存项 const unifiedCacheKey = `StoreService_getItemById_${this.layout.emp.id}`; // 新增传递itemId参数,供缓存逻辑定位具体项 return this.cacheS.getOrSetCache(unifiedCacheKey, id, this.http.get(`${environment.API_URL}item/getById/${id}`), 300000); }
2. 重写getOrSetCache方法(适配数组缓存)
getOrSetCache( key: string, itemId: string | number, request: Observable<any>, msToExpire = 3600000 ): Observable<any> { // 读取现有缓存,指定类型为包含数组data和过期时间exp的结构 let cache: { data: Array<any>, exp: number } | null = JSON.parse(localStorage.getItem(key)); // 1. 检查缓存是否有效,同时查找对应id的item if (cache && cache.exp > Date.now()) { const targetItem = cache.data.find(item => item.id === itemId); if (targetItem) { return of(targetItem); } } // 2. 缓存无效或未找到目标项,发起请求并更新缓存 return request.pipe( tap(newItem => { let updatedCache; if (cache && cache.exp > Date.now()) { // 缓存未过期:替换数组中已存在的同id项,不存在则追加 const updatedData = cache.data.map(item => item.id === itemId ? newItem : item ); if (!updatedData.some(item => item.id === itemId)) { updatedData.push(newItem); } updatedCache = { data: updatedData, exp: Date.now() + msToExpire }; } else { // 缓存过期或不存在:创建新的数组缓存 updatedCache = { data: [newItem], exp: Date.now() + msToExpire }; } localStorage.setItem(key, JSON.stringify(updatedCache)); }) ); }
关键说明
- 统一Key:确保同一员工的所有item数据都存储在
StoreService_getItemById_${员工ID}这一个LocalStorage项中 - 数组操作:读取时先在缓存数组中匹配目标ID,更新时保留其他有效项,避免重复存储
- 过期逻辑:采用整体缓存过期策略(也可根据需求修改为单个item独立过期,只需给数组中每个元素添加
exp字段即可)
内容的提问来源于stack exchange,提问作者Leonardo Lima
相关产品推荐
相关产品推荐

