簡體   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