Reputation: 145
I'm creating Ionic 4 plus Angular app, And I'm using Native Storage to save application data locally. below code I'm using but when I call get value it given null everytimes.
this.storage.set('myValue', this.value);
this.storage.get('myValue').then(value => {
console.log('My value: ' + value);
})
result given My value:null
Upvotes: 0
Views: 609
Reputation: 371
Hi @gaus Make sure you’re waiting on storage.ready() before trying to interact with it. something like that
this.storage.ready().then(() => {
return this.storage.get('myValue');
});
or you can use local storage instead of that
Upvotes: 0
Reputation: 145
We need to remember that get and set are async calls.We need to get after the set has been completed.Within the callback of the set we need to call get,That is why we are getting stale values.
Upvotes: 0
Reputation: 3966
The main idea will be that we are going to store an array of all keys we used so we can loop through it and remove the data for each key
Let's assume the following example:
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));
});
}
}
Now all you need to call clearData()
,
Here the Storage documentation.
Upvotes: 1