簡體   English   中英

嘗試從本地存儲檢索數據的問題

[英]Problems trying to retrieve data from local storage

我試圖從這個用 IONIC 和 ANGULAR 制作的應用程序中的離子本地存儲中檢索一些數據。 仍然看不到我忽略了什么,但是一旦觸發過程,數據就不會暴露。

假設我以這種方式安裝了所有必要的插件后,在我的離子存儲中設置了數據:

DataStorageService

import { Storage } from "@ionic/storage";

allMoviesfavorites: MovieSelectedDetails[] = [];

  saveAtStorage(movieToSave: MovieSelectedDetails) {
     ....asigning some value to variable allMoviesfavorites...

     this.storage.set("favorites", this.allMoviesfavorites);
  }

同樣在同一個服務中,我建立了以這種方式檢索它的方法

DataStorageService

import { Storage } from "@ionic/storage";

 allMoviesfavorites: MovieSelectedDetails[] = [];

constructor( private storage: Storage ) { this.loadfavoritesinStorage(); }
 
OPTION1
loadfavoritesinStorage() {
    this.storage.get("favorites").then((result) => {
      if (result == null) {
        result = [];
      }
      this.allMoviesfavorites = result;
      
    });

    return this.allMoviesfavorites;
  }

OPTION 2
 async loadfavoritesinStorage() {
    return this.storage.get("favorites").then((result) => {

       if (result == null) {
        result = [];
      }
      this.allMoviesfavorites =  result;
      console.log(result);
      

      return this.allMoviesfavorites;
    });
  }

如您所見,只需到達我在那里設置的所有數據的本地存儲容器,一旦到達那里,無論我得到什么結果,都會分配給之前初始化為空數組的變量 allMoviesFavorite。

然后在元素上,我想公開我在 ngOnInit 方法上觸發的數據,一個調用服務並執行任務的功能,將從服務帶來的數據分配給變量 moviesInFavorite,這將在 HTML 中循環以圖形方式顯示所有數據. 此外,我記錄了為了檢查而帶來的任何數據,但我沒有收到任何數據

Tab

import { DataStorageService } from "../services/data-storage.service";


moviesInFavorites: MovieSelectedDetails[] = [];
  constructor(private storageservice: DataStorageService) {}

  ngOnInit() {
    this.getFavorites();
  }

  async getFavorites() {
    let moviesInFavorites = await this.storageservice.loadfavoritesinStorage();
    console.log(moviesInFavorites);
    return (this.moviesInFavorites = moviesInFavorites);
  }

在此處輸入圖片說明 在此處輸入圖片說明

我怎樣才能改善這個問題?

問題是您在從存儲加載數據的異步代碼allMoviesfavorites之前返回allMoviesfavorites

這應該有效:

loadfavoritesinStorage() {
  return this.storage.get("favorites").then((result) => {
    if (result == null) {
      result = [];
    }

    this.allMoviesfavorites = result;
    
    return this.allMoviesfavorites; // <-- add the return here!      
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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