【问题标题】:Problems to get the data from Ionic Storage从 Ionic Storage 获取数据的问题
【发布时间】:2023-03-03 22:12:01
【问题描述】:

我的 Ionic-Storage 有问题。 我想将一个布尔值保存到存储中。该动作由离子切换触发。如果切换为 on=true,否则为 false。所以我创建了一个服务,可以保存和获取数据。

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)
      })
  }

问题来了…… 我想在组件中获取这些数据。像这样: 组件.ts

let saveWorkplace: boolean;
[...]
async setData(){
    await this.storage.getItem().then((name) => {
      console.log("Key: "+ name)
    })
  }

我想从存储中获取值(真或假),然后应该在 saveWorkplace 中定义。

如果我在 Component.ts 中 console.log 这个属性,我会得到一个未定义的对象。但是,如果我 console.log Storage.ts 中的属性,我会得到一个 Value(See Image)

我不知道如何才能只得到值真或假。

希望有人能帮帮我

【问题讨论】:

  • 您是否遇到任何错误?如果您在 Component.ts 中进行了依赖注入,这应该可以工作

标签: javascript angular ionic-framework storage ionic-storage


【解决方案1】:

您的getItem() 没有返回值。将其更改为:

async getItem() {
    return await this.storage.get(ITEM_KEY);
}

【讨论】:

  • 感谢您的帖子!不幸的是,在 component.ts 中使用 Console.log,我现在得到了“ZoneAwarePromise”的输出。问题是,我需要值“真”或“假”我怎么能得到这个?这是我尝试过的:await this.storage.get(ITEM_KEY).then((res)=>{ return res }); 不幸的是没有成功...但是如果我 console.log "res",true 或 false 出来了。
  • 您的服务中的“this.storage”是什么?
【解决方案2】:

您需要确保跟踪您返回的内容(承诺或价值)并相应地更新您的代码:

服务:

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);

}

在您的组件中,因为您返回承诺,您可以使用异步:

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;

    })
};

【讨论】:

  • 谢谢!!为了让组件每次都检索它,我在 ngOnInit 中额外添加了它。
  • 酷!是的,尽量减少使用存储等异步事物的工作是一种方法!
  • 您知道如何实现,如何在 ngOnInit 中调用异步方法吗?不幸的是,您不能向 ngOnInit 添加“等待”。在很多情况下你需要这个。
  • 是的,让我补充一下
  • 为 getData 方法添加了“return”,以及如何在 ngOnInit 中调用它。您还可以查看 Stackoverflow 以获取有关如何在 ngOnInit 中调用异步方法的答案,并且您可能只需在 ngOnInit 前面添加“async”并等待。
猜你喜欢
  • 2018-02-03
  • 2019-05-24
  • 2022-01-17
  • 2018-08-25
  • 2011-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多