Building an Ionic 3 Shopping Cart App with Firebase Realtime Database – Part 3

n

n
nHello friends, am sorry this part is coming so late. I have been very busy lately.
n
nIn part 2 of this series, the home page of the app where products are listed was done. nn

nnnnnIn this part I will walk you through the process of building the product details page, cart and order placement.
n
nnThe idea will be whenever customers clicks on any product in the home page, they should be presented with a product details page that will show a bigger sliding product images and other details.
n
n

nThe Single Product Page

nThe single product page we will be building will look like this:
n
n

n

n

n

nbuilding-ionic-3-shopping-cart-app-with-firebase-realtime-database nnnnn
Product Single Page

n
nnn

nThe Required Plugin

n
nSince we will be implementing the add to cart in this part,  we will be using the Ionic Storage Native plugin.
n
nStorage is an easy way to store key/value pairs and JSON objects. Storage uses a variety of storage engines underneath, picking the best one available depending on the platform.
n
nLets start by installing ionic native storage like so:
n

 nionic cordova plugin add cordova-sqlite-storage --savennnpm install --save @ionic/storagen

n
nThe Code Walkthrough
n Let’s start by modifying our home page html markup.  Add click event to the product col like this
n
n

(click)="showDetails(product)"n

n
nThe full markup will now look like below:
n

n  n n            n  n  n   {{product.price | currency:'USD':true:'1.2-2'}}n   nnn  n    n n  nn

n
nThe next thing is to add the showDetails method to the home.ts file. n
n

showDetails(product){n   this.navCtrl.push("SinglePage",{product:product});    n}n

n
nThe function is pretty simple we are just sending the selected product to the single page using the NavController push method.
n
nAdd the single page by runnig this command.
n

ionic g page singlen

n
nModify the single.html page content to reflect the following:
n
n
n

nn n n n n n n nn n n nn n n n
n
n

n{{selectProduct?.name}}

n{{ selectProduct?.short_description }}
n

n{{ selectProduct?.price | currency:'USD':truen }}

n
nn n
n

n Quantityn

nn n n n n n
n

nAdd this below the content of the single.html page.
n
n

n    n    n      n         n                     n  n        n      n    n    n  n

n
nnnnnAdd the following code to the home.ts file so that the whole home.ts will look like this:
n
n
n

import { Component } from '@angular/core';nimport { IonicPage, NavController, NavParams, ToastController } from 'ionic-angular';n//import { Storage } from '@ionic/storage';nimport { CartProvider } from '../../providers/cart/cart';nn@IonicPage()n@Component({n  selector: 'page-single',n  templateUrl: 'single.html',n})nexport class SinglePage {n  selectProduct: any;n  productCount: number = 1;n  cartItems: any[];n  constructor(public navCtrl: NavController, public navParams: NavParams,n    private cartService: CartProvider, public toastCtrl: ToastController) {n    if (this.navParams.get("product")) {n      window.localStorage.setItem('selectedProduct', JSON.stringify(this.navParams.get("product")));n    }nnn  }n  ionViewDidEnter(){n    this.getSingleProduct();n  }nn n  getSingleProduct() {n    if (window.localStorage.getItem('selectedProduct') != 'undefined') {n      this.selectProduct = JSON.parse(window.localStorage.getItem('selectedProduct'))n    }n  }nn  ionViewDidLoad() {n    this.selectProduct = this.navParams.get("product");n    this.cartService.getCartItems().then((val) => {n      this.cartItems = val;n    })nn  }nn  decreaseProductCount() {n    if (this.productCount > 1) {n      this.productCount--;n    }nn  }nn  incrementProductCount() {n    this.productCount++;nn  }nn  addToCart(product) {n    var productPrice = this.productCount * parseInt(product.price);n    let cartProduct = {n      product_id: product.id,n      name: product.name,n      thumb: product.thumb,n      count: this.productCount,n      totalPrice: productPricen    };n    this.cartService.addToCart(cartProduct).then((val) => {n      this.presentToast(cartProduct.name);n    });n  }nnn  presentToast(name) {n    let toast = this.toastCtrl.create({n      message: `${name} has been added to cart`,n      showCloseButton: true,n      closeButtonText: 'View Cart'n    });nn    toast.onDidDismiss(() => {n      this.navCtrl.push('CartPage');n    });n    toast.present();n  }nnn}nnn

n
nLet’s add our cart provider by running this command:nn
n

ionic g provider cartn

n
n

nThe Cart Providernn

n

import { Injectable } from '@angular/core';nimport { Storage } from '@ionic/storage';nnconst CART_KEY = 'cartItems';nn@Injectable()nexport class CartProvider {nn  constructor(public storage: Storage) {nn  }nn  addToCart(product) {n    return this.getCartItems().then(result => {n      if (result) {n        if (!this.containsObject(product, result)) {n          result.push(product);n          return this.storage.set(CART_KEY, result);n        } else {n          let index = result.findIndex(x => x.product_id == product.product_id);n          let prevQuantity = parseInt(result[index].count);n          product.count = (prevQuantity + product.count);n          let currentPrice = (parseInt(product.totalPrice) * product.count);n          product.totalPrice =currentPrice;n           result.splice(index, 1);n          result.push(product);n          return this.storage.set(CART_KEY, result);n        }nn      } else {n        return this.storage.set(CART_KEY, [product]);n      }n    })n  }nn  removeFromCart(product) {n    return this.getCartItems().then(result => {n      if (result) {n        var productIndex = result.indexOf(product);n        result.splice(productIndex, 1);n        return this.storage.set(CART_KEY, result);n      }n    })n  }nn  removeAllCartItems() {n    return this.storage.remove(CART_KEY).then(res => {n      return res;n    });n  }nnn  containsObject(obj, list): boolean {n    if (!list.length) {n      return false;n    }nn    if (obj == null) {n      return false;n    }n    var i;n    for (i = 0; i < list.length; i++) {n      if (list[i].product_id == obj.product_id) {n        return true;n      }n    }n    return false;n  }nnnn  getCartItems() {n    return this.storage.get(CART_KEY);n  }nn}nn

nnnnnnWatch out for part four because of the length of this post.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top