I'm using Ionic's storage to save javascript data object which has several attributes. I'm trying to create a favorite list which can fetch data from ionic storage.
Here's my data provider TS file.
private items: any[] = [
{
"name": "item 01",
"description": "this is item 01",
"id": "1"
},
{
"name": "item 02",
"description": "this is item 02",
"id": "2"
},
{
"name": "item 03",
"description": "this is item 03",
"id": "3"
},
{
"name": "item 04",
"description":"this is item 04",
"id":"4"
}
]
and I'm saving items on my html file using a button. the main HTML file is using *ngFor let of directive to fetch the items from the provider.
Main HTML:
<div *ngFor="let item of items">
<h2>{{item.name}}</h2>
<p>{{item.description}}</p>
<button (click)="saveToFav(item)">Save to favorites</button>
</div>
Main TS file:
savToFav(item) {
this.storage.set(this.item.id, this.item);
}
This saves the item with its attributes to Ionic storage. I can see that showing up on my browser's inspect -> application page.
and I'm trying to fetch items from ionic storage to a favorite HTML page.
Favorite HTML page:
<div *ngFor="let item of items">
<h2>{{item.name}}</h2>
<p>{{item.description}}</p>
<button (click)="remove(item)">Remove from favorites</button>
</div>
Favorite TS file
this.platform.ready().then(() => {
this.storage.get(this.item);
});
But this really doesn't load anything on favorite html page..
What should I do to fetch every item stored in Ionic storage to favorite HTML page?
Thanks in advance,
You are using storage get and set function in wrong manner, All the favorite items must be stored in the single key so that later when required you can have all the list of the favorites. It should be like the below one
savToFav(item) {
this.storage.get('favoritesList')
.then((fav)=>{
if(fav == null){
fav = [];
}
//This will fetch the old items and push the new item in array
fav.push(item); return fav;
})
.then((fav)=>{
//this will store the new update favorite list array in storage.
this.storage.set('favoritesList',fav);
})
}
//Favorite ts file you can use it like below
this.storage.get('favoritesList').then((fav)=>{
//you can asssing it any variable and use in your *ngFor loop
this.myFavList = fav;
})
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments