Issue
Good day everyone, Please I need your help. I am trying to get an array from storage that displays my cart items, but my only problem is that storage values don't display until I reload the page. Please help me. thanks.
cart.ts
cartData: any = [] ;
baseProducts: any =[] ;
constructor(private changeRef: ChangeDetectorRef, private storage: Storage) {
this.storage.forEach((data)=>{
let storedProducts = {};
let parseFromStorage = JSON.parse(data);
this.cartData.push(parseFromStorage);
storedProducts['product_id'] = parseFromStorage.id;
storedProducts['price'] = parseFromStorage.price;
storedProducts['quantity'] = 1;
this.baseProducts.push(storedProducts);
}).then(()=>{
this.changeRef.detectChanges();
console.log('parse product', this.baseProducts);
});
}
cart.html
<ion-row *ngIf="cartData.length > 0">
<ion-col size="12" *ngFor="let item of cartData; let j = index">
<ion-card style="margin-top: 0; margin-bottom: 0;">
<ion-list class="ion-no-padding">
<ion-item>
<ion-thumbnail slot="start" *ngIf="cartData">
<img [src]="item.images[0].src">
</ion-thumbnail>
<ion-label>
<h4><b>{{ item.name }}</b></h4>
<p>${{baseProducts[j].price * baseProducts[j].quantity | number:'1.0-0'}}
</p>
</ion-label>
<ion-icon color="danger" name="trash-bin-outline" (click)="removeFromCart(j, item)"></ion-icon>
</ion-item>
</ion-list>
</ion-card>
</ion-col>
</ion-row>
Solution
Add code into ionViewWillEnter() . It will call your storage everytime.
constructor(private changeRef: ChangeDetectorRef, private storage: Storage) { }
//Writen code in below will execute everrytime.
ionViewWillEnter() {
this.cartData = [];
this.baseProducts = [];
this.storage.forEach((data)=>{
let storedProducts = {};
let parseFromStorage = JSON.parse(data);
this.cartData.push(parseFromStorage);
storedProducts['product_id'] = parseFromStorage.id;
storedProducts['price'] = parseFromStorage.price;
storedProducts['quantity'] = 1;
this.baseProducts.push(storedProducts);
}).then(()=>{
this.changeRef.detectChanges();
console.log('parse product', this.baseProducts);
});
}
Answered By - Shabbir Dhangot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.