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