[英]Problems to get the data from Ionic Storage
I have a problem with the Ionic-Storage.我的离子存储有问题。 I want to save a boolean into the storage.
我想将 boolean 保存到存储中。 The action is triggered by an ion-toggle.
该动作由离子切换触发。 If the toggle is on= true, otherwise false.
如果切换为 on=true,否则为 false。 So I have create a service, which can save and get the data.
所以我创建了一个服务,可以保存和获取数据。
Storage-Service.ts存储服务.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
像这样: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.我想从存储中获取值(真或假),然后应该在 saveWorkplace 中定义。
If I console.log this properties in the Component.ts I get an undefined object.如果我在 Component.ts 中 console.log 这个属性,我会得到一个未定义的 object。 But if i console.log the property in Storage.ts I get an Value( See Image )
但是,如果我 console.log Storage.ts 中的属性,我会得到一个值(见图)
I dont know how I can get only the Value true or false.我不知道如何才能仅获得值真或假。
I hope anyone can help me我希望有人能帮助我
Your getItem()
is not returning the value.您的
getItem()
没有返回值。 Change it to:将其更改为:
async getItem() {
return await this.storage.get(ITEM_KEY);
}
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:在您的组件中,因为您要返回 promise,您可以使用异步:
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)读取这些值,您可以这样做:
ngOnInit() {
this.getData().then( saved => {
console.log(saved)
// the rest of init code that depends on the value;
})
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.