【发布时间】:2022-08-17 23:32:47
【问题描述】:
我有这段代码,它的想法是将产品保存在本地存储中,当产品已经在本地存储中时,它不会再次发出请求
getItemById(id) {
// return this.http.get(`${environment.API_URL}item/getById/${id}`);
return this.cacheS.getOrSetCache(`StoreService_getItemById_${id}_${this.layout.emp.id}`, this.http.get(`${environment.API_URL}item/getById/${id}`), 300000);
}
getOrSetCache(key: string, request: Observable<any>, msToExpire = 3600000): Observable<any> {
let cache: any = {};
const keyy = \'StoreService_getItemById_teste\';
cache = JSON.parse(localStorage.getItem(keyy));
return (cache?.data && (cache?.exp > Date.now())) ?
of(cache.data) :
request.pipe(
tap(v => {
let arr: any[] = [];
let string = localStorage.getItem(keyy);
if (string) arr = JSON.parse(string);
console.log(arr)
arr.push({data: v, exp: (Date.now() + msToExpire)});
localStorage.setItem(keyy, JSON.stringify(arr));
})
);
}
我如何映射 id 以便当我已经在 localstorage 中拥有它时它不会发出对该 id 的请求?
还想知道如果当前时间等于或大于此时间戳,我如何查看过期日期,它将其从缓存中删除并再次执行查询
标签: javascript angular local-storage