【问题标题】:How to properly set and get using native storage ionic 4?如何正确设置和使用本机存储 ionic 4?
【发布时间】:2019-05-23 15:32:16
【问题描述】:

我正在创建 Ionic 4 plus Angular 应用程序,并且我正在使用 Native Storage 在本地保存应用程序数据。下面是我正在使用的代码,但是当我调用 get value 时,它​​每次都给出 null。

this.storage.set('myValue', this.value);

this.storage.get('myValue').then(value => {
console.log('My value: ' + value);
}) 

结果给定我的值:null

【问题讨论】:

  • 你的意思是要清除浏览器的cashe?
  • 每当您使用键设置值时,将所有键存储在一个数组中,然后循环遍历它并为每个元素调用 storage.remove(key)

标签: typescript angular7 ionic4


【解决方案1】:

主要思想是我们将存储我们使用的所有键的数组,以便我们可以循环遍历它并删除每个键的数据

让我们假设以下示例:

firstService

export clas FirstService {
   constructor(garbage: GarbageCollecterService){}

  // Let's assume here you are storing data in memroy
  storeDataInMemory(key1) {
    ...
    // At the end of the function store the key in an array , We need it later
    this.garbage.storeAllKeys(key);
   }
}

secondService

export clas SecondService {
   constructor(garbage: GarbageCollecterService){}
  storeDataInMemory(key2) {
    ...
    // At the end of the function store the key in an array , We need it later
    this.garbage.storeAllKeys(key);
   }
}
export class GarbageCollecterService {

   storeAllKeys(key) {
      let totalArray = [];
      // In case you have keys before
      storage.get('AllKeys').then(AllKeys => {
         totalArray = AllKeys
         totalArray.push(key);
      });

    }

   // The following function will take all keys out of memory and looping over them and foreach one will remove the data related to it
    clearAllData() {
     let totalArray = [];
     storage.get('AllKeys').then(AllKeys => {
      totalArray = AllKeys
      totalArray.foreach(ele => storage.remove(ele));
     });

    }
}

现在您只需拨打clearData()

这里是Storage 文档。

【讨论】:

  • 所以你没有为所有服务使用相同的存储对象,我的意思是所有应用程序,创建一个不同的服务,它只负责处理从同一个对象获取、设置和删除数据跨度>
  • 您是在使用相同的存储对象还是为每个服务或页面创建一个新对象?
  • 也许你不明白,请随意在你的所有页面上创建一个存储对象
【解决方案2】:

我们需要记住,get 和 set 是异步调用。我们需要在 set 完成后获取。在 set 的回调中我们需要调用 get,这就是我们获取陈旧值的原因。

【讨论】:

    【解决方案3】:

    嗨@gaus 确保在尝试与 storage.ready() 交互之前等待它。类似的东西

     this.storage.ready().then(() => {
          return this.storage.get('myValue');
        });
    

    或者您可以使用本地存储来代替它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 2019-06-09
      • 1970-01-01
      • 1970-01-01
      • 2019-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多