簡體   English   中英

從 Ionic Storage 獲取數據的問題

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM