Reputation: 1295
Im trying to retrieve some data from ionic local storage in this app made in IONIC and ANGULAR. Still can't see what i'm ommitting but the data doesn't get exposed once the process is triggered.
Lets say i set the data in my ionic storage afeter having installed all the neccesary plugins in this way :
DataStorageService
import { Storage } from "@ionic/storage";
allMoviesfavorites: MovieSelectedDetails[] = [];
saveAtStorage(movieToSave: MovieSelectedDetails) {
....asigning some value to variable allMoviesfavorites...
this.storage.set("favorites", this.allMoviesfavorites);
}
Also in the same service i establish the method to retrieve it in this way
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;
});
}
As you see simply reach my local storage container of all the data i have been setting there, and once reached there whatever the result i got would be asigned to the variable allMoviesFavorite previously initialized as an empty array.
Then on the element i want to expose that data i trigger on the ngOnInit method a fucntion that calls the service and does the taks, asigning the data brought from service to the variable moviesInFavorite, that would be looped in the HTML to display graphically all data . Also i log whatever the data is brought in order to check, but i don't receive any data
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);
}
How could i improve the problem?
Upvotes: 1
Views: 489
Reputation: 44659
The issue is that you're returning allMoviesfavorites
before the async code that loads the data from the storage is done.
This should work:
loadfavoritesinStorage() {
return this.storage.get("favorites").then((result) => {
if (result == null) {
result = [];
}
this.allMoviesfavorites = result;
return this.allMoviesfavorites; // <-- add the return here!
});
}
Upvotes: 1