[英]how to save an array in localstorage
我目前有這段代碼,它保存在本地存儲中,但它會生成幾個對象,我想將所有內容存儲在一個數組中
getItemById(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 = {};
cache = JSON.parse(localStorage.getItem(key));
return (cache?.data && (cache?.exp > Date.now())) ?
of(cache.data) :
request.pipe(tap(v => {
localStorage.setItem(key, JSON.stringify({data: v, exp: (Date.now() + msToExpire)}));
}));
}
此代碼有效,但我想加入所有StoreService_getItemById_
,使用此代碼它在單個StoreService_getItemById_
中創建數組,如果您注意到圖像有幾個名為 StoreService_getItemById_ 的本地存儲,我希望它只有一個並且在里面它有數組格式的對象
localStorage.setItem(key, JSON.stringify({data: [v], exp: (Date.now() + msToExpire)}));
聽起來您想將 append 項目添加到本地存儲中的數組中。 問題是,本地存儲只保存字符串。 您可以解析字符串以將其轉換為數組, append 一個新項目,然后覆蓋舊字符串。
const key = 'my-array-key';
const someData = { name: 'name', id: 'abcdef' };
const msToExpire = 5000;
// Convert string to array, initializes empty array if string is empty
let arr: any[] = [];
let string = localStorage.getItem(key);
if (string) arr = JSON.parse(string);
// Push a new item and overwrite the old string
arr.push({data: someData, exp: (Date.now() + msToExpire)});
localStorage.setItem(key, JSON.stringify(arr));
我不確定你想如何構建 function 但這個例子應該給你一個大致的想法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.