I have a problem with the Ionic-Storage. I want to save a boolean into the storage. The action is triggered by an ion-toggle. If the toggle is on= true, otherwise false. So I have create a service, which can save and get the data.
Storage-Service.ts
const ITEM_KEY = 'modal-myworkplace';
[...]
async setItem(value){
const res = await this.storage.set(ITEM_KEY,value)
console.log(res)
}
async getItem() {
await this.storage.get(ITEM_KEY).then((name) => {
console.log('The Keyvalue is: '+name)
})
}
Here is the problem... I want to get this data in an component. Like this: Component.ts
let saveWorkplace: boolean;
[...]
async setData(){
await this.storage.getItem().then((name) => {
console.log("Key: "+ name)
})
}
I want to get the value from the Storage (true or false) and this should then be defined in saveWorkplace.
If I console.log this properties in the Component.ts I get an undefined object. But if i console.log the property in Storage.ts I get an Value(See Image)
I dont know how I can get only the Value true or false.
I hope anyone can help me
You need to make sure you track what you return (Promise or value) and update your code accordingly:
Service:
setItem(value):Promise<any> {
this.storage.set(ITEM_KEY,value) // you can use .then here to check saved value.
}
getItem():Promise<any> {
return this.storage.get(ITEM_KEY);
}
In your component since you are returning promise you can use async:
async getData() {
return this.saveWorkplace = await this.storage.getItem()
};
Now if you feel the need to leverage async method and read these values at the page initialization time (ngOnInit), you can do so this way:
ngOnInit() {
this.getData().then( saved => {
console.log(saved)
// the rest of init code that depends on the value;
})
};