繁体   English   中英

如何查看数组中的id是否已存在于localstorage中

[英]how to see if id in array already exists in localstorage

我有这个 function,它将请求响应保存在 localStorage 中。 但我希望如果 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));
        })
    );
}

现在正如您在图像中看到的那样,它正在保存重复的 ID 在此处输入图像描述

我尝试了几种方法但没有成功,似乎我不能 map 数组中的每个项目console.log(cache) 在此处输入图像描述

您正在使用|| 健康)状况。 这就是您的 Api 始终调用您是否有数据的原因。就像在Or 条件下,如果您的一个条件从两者都为真(cache?.data && cache?.exp > Date.now()) || (cache?.data && cache?.data.find(item => item.data.id === id))然后你可以进入if块。

localStoragekey => value存储,用于搜索等更好IndexedDB 文档: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM