简体   繁体   中英

ionic 3 with storage

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

II 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM