Reputation: 807
I am using ionic 3 with storage.
First, i import storage in the app.module.ts
import { IonicStorageModule } from '@ionic/storage';
imports: [
IonicStorageModule.forRoot()
]
I developed Ecommerce app.If I add to any product to cart using storage.
Here is my code for Cart page.
<ion-row class="apply-coupon" *ngFor="let p of Cartproducts;let i=index">
<ion-col col-4>
<img src="{{p.P_IMAGES[0].URL}}" alt="product2">
</ion-col>
<ion-col col-8>
<h1>{{p.P_TITLE}}</h1>
<p class="subtitle">Subtitle</p>
<p class="code">Code: 123</p>
<div>
<button (click)="cancel(i)">Cancel X</button>
</div>
</ion-col>
</ion-row>
this.items.push(item);
this.storage.set('products',this.items);
item is a product detail.and I have displayed the cart count.
this.storage.get('products').then((data) => {
if(data != null)
{
this.Cartproducts=data;
console.log(this.Cartproducts);
}
});
here is my consoled value.
[
{
'Product_title':'Product name',
'Product desc':'product dec',
'id':1
},
{
'Product_title':'Product name',
'Product desc':'product dec'
'id':2
}
]
If I need to remove the last product.
this.Cartproducts.splice(i, 1);
console.log(this.Cartproducts);
this.storage.remove('products');
this.storage.set('products',this.Cartproducts);
Here is my consoled value.
[
{
'Product_title':'Product name',
'Product desc':'product dec',
'id':1
}
]
I remove the storage value in 'products'
Again I set the value products
I I need another product.so I am going to the product page and add the product.
But my result is
[
{
'Product_title':'Product name',
'Product desc':'product dec',
'id':1
},
{
'Product_title':'Product name',
'Product desc':'product dec'
'id':2
},
{
'Product_title':'Product name',
'Product desc':'product dec'
'id':3
}
]
But Actually, I remove the second product.Did not set to storage why?
Kindly advice me,
Thanks
Upvotes: 2
Views: 5574
Reputation: 687
try
this.storage.get('products').then((data) => {
if(data == null)
{
data=[];
}
this.items=data;//re-initialize the items array equal to storage value
this.items.push(item);
this.storage.set('products',this.items);
});
instead of
this.items.push(item); this.storage.set('products',this.items)
Upvotes: 4