我正在创建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);
})
给定我的值的结果:空
发布于 2019-05-20 23:45:21
主要思想是,我们将存储我们使用的所有键的数组,这样我们就可以遍历该数组并删除每个键的数据
让我们假设下面的例子:
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文档。
发布于 2019-05-21 14:57:39
我们需要记住,get和set是在set被completed.Within之后需要异步获取的,这就是为什么我们会得到陈旧的值。
发布于 2019-05-23 15:32:16
您好,@gaus,在尝试与storage.ready()交互之前,请确保您正在等待它。类似这样的东西
this.storage.ready().then(() => {
return this.storage.get('myValue');
});或者,您可以使用本地存储来代替它
https://stackoverflow.com/questions/56222687
复制相似问题