[英]how to see if id in array already exists in localstorage
I have this function, it saves the request response in localStorage.我有这个 function,它将请求响应保存在 localStorage 中。 but I would like that if the id already existed in the array it would not make the request again
但我希望如果 id 已经存在于数组中,它不会再次发出请求
getItemById(id) {
// return this.http.get(`${environment.API_URL}item/getById/${id}`);
return this.cacheS.getOrSetCache(id, `StoreService_getItemById_${id}_${this.layout.emp.id}`, this.http.get(`${environment.API_URL}item/getById/${id}`), 300000);
}
getOrSetCache(
id: any,
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()) ||
(cache?.data && cache?.data.find(item => item.data.id === id)) ?
of(cache.data) : request.pipe(
tap(v => {
let arr: any[] = [];
let string = localStorage.getItem(keyy);
if (string) arr = JSON.parse(string);
arr.push({
data: v,
exp: Date.now() + msToExpire
});
localStorage.setItem(keyy, JSON.stringify(arr));
})
);
}
now as you can see in the image it is saving duplicate ids现在正如您在图像中看到的那样,它正在保存重复的 ID
I tried a few ways but without success, it seems that I can't map each item in the array the console.log(cache)
我尝试了几种方法但没有成功,似乎我不能 map 数组中的每个项目
console.log(cache)
You are using ||您正在使用|| condition.
健康)状况。 That is a reason your Api always calls whether you have data or not.Like in Or condition If your one condition is true from both (cache?.data && cache?.exp > Date. now()) ||
这就是您的 Api 始终调用您是否有数据的原因。就像在Or 条件下,如果您的一个条件从两者都为真(cache?.data && cache?.exp > Date.now()) || (cache?.data && cache?.data.find(item => item.data.id === id)) then you can get into the if block.
(cache?.data && cache?.data.find(item => item.data.id === id))然后你可以进入if块。
localStorage
is key => value
storage, for searching etc. is better IndexedDB
. localStorage
是key => value
存储,用于搜索等更好IndexedDB
。 Docs: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API文档: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.