Gabriel Geelario
Gabriel Geelario

Reputation: 237

Reload page after delete item in IONIC4

Good day expert in the house. Please am currently building an e-commerce mobile app with ionic 4, am having difficulty updating my item-total summary when an item is deleted from the cart page.

This my cart.html page below

    <ion-header [translucent]="true">
  <ion-toolbar color="success">
    <ion-buttons slot="start">
      <ion-back-button defaultHref="products"></ion-back-button>
    </ion-buttons>
    <ion-buttons slot="end">
      <ion-icon slot="start" name="cart" [routerLink]="['/cart']"></ion-icon>
      <ion-badge color="primary">{{ cartItem }}</ion-badge>
    </ion-buttons>
    <ion-title>Cart</ion-title>
  </ion-toolbar>
</ion-header>


<ion-content>
  <!--DISPLAY OF NO ITEM -->
  <div *ngIf="cartData.length == 0" class="ion-padding" >
    <ion-row size="12" disabled="true" class="ion-padding">
      <ion-col class="ion-padding-vertical">
        <h5 class="ion-text-center ion-padding-vertical">There is no Item in your cart...!</h5>
        <ion-button expand="block" color="success" [routerLink]="['/products']" class="ion-text-capitalize" style="font-size: 18px;">Browse farms</ion-button>
      </ion-col>
    </ion-row>
  </div>
  <!--DISPLAY OF NO ITEM --> 
  <ion-card>
    <ion-list *ngIf="cartData.length > 0" >
      <ion-list-header>
        <ion-label class="headerTitle">Items in cart</ion-label>
        <ion-button [routerLink]="['/products']" >
          <ion-icon slot="icon-only"   name="add-circle" class="add_icon" color="success"></ion-icon>
        </ion-button>
      </ion-list-header>


      <ion-item *ngFor="let item of cartData; let j = index" >
        <ion-thumbnail slot="start">
          <img [src]="item.images[0].src">
        </ion-thumbnail>
        <ion-label>
          <h4>{{ item.name }}</h4>
          <p>Amount: <span style="color: rgb(26, 185, 26); font-weight: 400; font-size: 17px;">₦{{ baseProducts[j].price * baseProducts[j].quantity | number:'1.0-0'}}</span></p>
          <p >Returns: ‎₦{{ item.meta_data[1].value * baseProducts[j].quantity | number:'1.0-0' }}</p>
          <!--<ion-item>
           <ion-icon name="remove" class="decrement" (ionChange)="changeCartItemQty(baseProducts[j])"></ion-icon><span>{{ quantityValue }}</span><ion-icon (click)="increment()" name="add" class="increment"></ion-icon>
          </ion-text>-->  
          <ion-item>
            <ion-label>Change Quantity</ion-label>
              <ion-select value="brown" 
              okText="Okay" 
              cancelText="Dismiss" 
              [(ngModel)]="baseProducts[j].quantity" 
              (ionChange)="changeCartItemQty(baseProducts[j])">
                <ion-select-option value="1">1</ion-select-option>
                <ion-select-option value="2">2</ion-select-option>
                <ion-select-option value="3">3</ion-select-option>
                <ion-select-option value="4">4</ion-select-option>
                <ion-select-option value="5">5</ion-select-option>
                <ion-select-option value="6">6</ion-select-option>
                <ion-select-option value="7">7</ion-select-option>
                <ion-select-option value="8">8</ion-select-option>
                <ion-select-option value="9">9</ion-select-option>
                <ion-select-option value="10">10</ion-select-option>
              </ion-select>
            </ion-item>
        </ion-label> 

        <ion-button color="danger" (click)="removeFromCart(j, item)">
          <ion-icon slot="icon-only" name="trash"></ion-icon>
        </ion-button>
      </ion-item>
    </ion-list>

  </ion-card>


</ion-content>


<ion-footer *ngIf="cartData.length > 0" [routerLink]="['/checkout']">
  <ion-list >
    <ion-item >

Sub total

₦{{ calculatePrice() | number:'1.0-0'}}

Total Payment ₦{{ calculatePrice() | number:'1.0-0' }}

  <ion-button expand="full" color="success"  class="ion-text-capitalize">Proceed to checkout <ion-icon slot="end" name="arrow-forward-outline"></ion-icon></ion-button>
</section>

</ion-footer>

my cart.ts file

import { Storage } from '@ionic/storage';
import { Component, OnInit } from '@angular/core';
import { CartserviceService } from '../services/cartservice.service';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.page.html',
  styleUrls: ['./cart.page.scss'],
})
export class CartPage implements OnInit {

  /* use below 4 variables at beginning so that cart page html works properly */
  cartData:any = [];
  baseProducts:any = [];
  totalPrice: number = 0;
  show: boolean = true;
  cartItem: number = 0;
  quantityValue:number = 1;

  constructor(private storage: Storage, private cart: CartserviceService) {
    this.cart.keepCartItemsOnRefresh();

    // products added to carts  
    this.storage.forEach((data)=>{
      let storedProducts = {};
      this.cart.keepCartItemsOnRefresh();
      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(()=>{
      console.log('parse-prudcts', this.baseProducts)
    });
   }

  ngOnInit() {
    this.cart.cartItems.subscribe((value) =>{
      this.cartItem = value;
    });
  }



    //update in products

    changeCartItemQty(currentItem){
      this.baseProducts.forEach((productToUpdate) => {
        if(productToUpdate.product_id == currentItem.product_id){
          productToUpdate.quantity = parseInt(currentItem.quantity);
        }
      });
      this.cart.quantityUpdatedProducts = this.baseProducts;
      console.log('Changed Quantity on cart',this.cart.quantityUpdatedProducts);
    }
  // Delete item from cart
  removeFromCart(index, item){
  this.cartData.splice(index,1);
  let pId = item.id;
  this.storage.remove(`product_${pId}`);
  this.cart.keepCartItemsOnRefresh();

  }



  // calulate farm price
  calculatePrice(){
    this.totalPrice = 0;
    let farmPrice = 0;
    this.baseProducts.forEach((product)=>{
    farmPrice = product.price * product.quantity;
    this.totalPrice += farmPrice;
   });
   return this.totalPrice   
  } 
}

I want the item total to update to the current item total in the cart when I delete an item from the cart

Upvotes: 0

Views: 811

Answers (1)

Himanshu Patni
Himanshu Patni

Reputation: 195

if you want to reload the complete page you can go for "window.location.reload()" or if you just want the updated data you can recall the specific API after deleting.

Upvotes: 1

Related Questions