尝试从本地存储中检索数据时出现问题

问题描述

我正在尝试使用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方法上触发一个函数,该函数调用服务并执行任务,将从服务带来的数据分配给变量movieInFavorite,该变量将在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);
  }

enter image description here

enter image description here

我该如何解决这个问题?

解决方法

问题是您要从存储中加载数据的异步代码完成之前返回allMoviesfavorites

这应该有效:

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

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