[英]Problems to get the data from Ionic Storage
我的离子存储有问题。 我想将 boolean 保存到存储中。 该动作由离子切换触发。 如果切换为 on=true,否则为 false。 所以我创建了一个服务,可以保存和获取数据。
存储服务.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)
})
}
这是问题......我想在一个组件中获取这些数据。 像这样:Component.ts
let saveWorkplace: boolean;
[...]
async setData(){
await this.storage.getItem().then((name) => {
console.log("Key: "+ name)
})
}
我想从存储中获取值(真或假),然后应该在 saveWorkplace 中定义。
如果我在 Component.ts 中 console.log 这个属性,我会得到一个未定义的 object。 但是,如果我 console.log Storage.ts 中的属性,我会得到一个值(见图)
我不知道如何才能仅获得值真或假。
我希望有人能帮助我
您的getItem()
没有返回值。 将其更改为:
async getItem() {
return await this.storage.get(ITEM_KEY);
}
您需要确保跟踪您返回的内容(承诺或价值)并相应地更新您的代码:
服务:
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);
}
在您的组件中,因为您要返回 promise,您可以使用异步:
async getData() {
return this.saveWorkplace = await this.storage.getItem()
};
现在,如果您觉得需要利用异步方法并在页面初始化时(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.