【问题标题】:How do I remove a date by its key from local Storage in angular如何按日期从本地存储中删除日期
【发布时间】:2019-10-02 11:51:00
【问题描述】:

我正在尝试从本地存储中清除对象 (collectionFilter) 中的字段,使用 localStorage.removeItem('collectionFilter') 除日期字段外,其他字段已被删除,(请注意,我是 javascript 和 angular 新手)

我试过了,但它不适合我

Trying to remove particular value from local storage key

下面是代码

localStorage.removeItem('collectionFilter');
localStorage.setItem('collectionFilter', JSON.stringify(data));
this.collectionService.searchCollection(filter, event.itemsPerPage, offset)
  .subscribe((payload) => {
    if (this.page !== event.page) {
      return;
    }
    this.queryResult = payload.queryResult;
    this.totalAmount = payload.sum;
    this.working = false;
  });

本地存储数据

agency: ""
endDate: "2019-10-03"
invoiceAccountCode: ""
paymentChannel: ""
paymentProviderReference: ""
prr: ""
receiptNumber: ""
revenueItem: ""
revenueSource: "6"
startDate: "2019-01-01"
tin: ""

预期结果

agency: ""
endDate: ""
invoiceAccountCode: ""
paymentChannel: ""
paymentProviderReference: ""
prr: ""
receiptNumber: ""
revenueItem: ""
revenueSource: ""
startDate: ""
tin: ""

【问题讨论】:

  • 您可以添加存储在localStorage中的示例数据吗?
  • 删除密钥后您想要的预期数据是什么。您的方法是正确的。您遇到了什么错误
  • @ShivShankarNamdev 我已经添加了预期的数据
  • 如果要清除“所有”属性,最简单的方法是将collectionFilter 设置为所有属性为空。

标签: javascript angular date


【解决方案1】:

你也可以这样做的另一种方式

let savedCredentials = sessionStorage.getItem(credentialsKey) || localStorage.getItem(credentialsKey);
savedCredentials = JSON.parse(savedCredentials);
savedCredentials['property_ID'] = propertyId;
savedCredentials['name'] = propertyName;
savedCredentials['address'] = address;
savedCredentials['businessDate'] = businessDate;
const storage = this.isSessionStorageOrLocal();
if (storage === 'local') {
  localStorage.removeItem(credentialsKey);
  localStorage.setItem(credentialsKey, JSON.stringify(savedCredentials));
} else if (storage === 'session') {
  sessionStorage.removeItem(credentialsKey);
  sessionStorage.setItem(credentialsKey, JSON.stringify(savedCredentials));
}

【讨论】:

    【解决方案2】:

    这样的事情会做:

    const keys = ["endDate", "startDate", "revenueSource"];
    
    keys.forEach(key => localStorage.setItem(key, ""));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-15
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      • 1970-01-01
      相关资源
      最近更新 更多