[英]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));
})
);
}
您正在使用|| 健康)狀況。 這就是您的 Api 始終調用您是否有數據的原因。就像在Or 條件下,如果您的一個條件從兩者都為真(cache?.data && cache?.exp > Date.now()) || (cache?.data && cache?.data.find(item => item.data.id === id))然后你可以進入if塊。
localStorage
是key => value
存儲,用於搜索等更好IndexedDB
。 文檔: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.