nn
nnn
n
n
n
nn
nnnnn
nnnIn part three of this tutorial series, we stopped at creating the cart provider. Lets start by creating the cart page. By the time we finished the cart page, the result will look like what we have below.
n
n
n
nn
n
n
nThe Cart Pagen
nCreate an ionic page named cart using the cli command like so:nn
n
ionic g page cartnn
nReplace the html code with the following codes:nnn
n
n nn n nn Your Cartn nn nnnnnnn
nn nYour cart is emptynnnnn n n n
nn{{itm.name}}
nnn n nn nn
nnQty: {{itm.count}}nnnn nnn nnn nn nn n
nNext is the scss file to make it look good. Add the below css code to the cart.scss file:nnn
n
page-cart {n .fixed-content,n .scroll-content {n background: #EAEAEA;nn .empty-cart{n margin-top: 50%;n height: 100%;n .empty-results{n ion-icon{n font-size: 105px;n color: rgb(175, 175, 175);n }nn p{n font-size: 30px;n color: rgb(175, 175, 175);n }n }n }nnn ion-card {n margin: 10px 0;n width: 100%;n min-height: 85px !important;n ion-card-content {n padding: 8px !important;n ion-col {n padding: 0;n span.price {n right: 0;n position: absolute;n bottom: 0;n }n span.remove {n left: 0;n position: absolute;n bottom: 0;n background: #ff0000;n padding: 3px 10px;n color: #fff;n }n ion-item {n min-height: 75px !important;n padding: 0 !important;n .item-inner {n padding: 0 !important;n ion-label {n min-height: 75px !important;n margin: 0 !important;n ion-avatar {n min-height: 75px !important;n img {n border-radius: 0 !important;n width: 80%;n height: 70px;n margin-right: 0 !important;n }n }n }n }n }n }n }n } //End Ion-Cardn ion-card:first-child {n margin-top: 0 !important;n }n }n ion-footer.single-footer {n background: #ECECE2;n }n}n
n
nnn
n
nnThe Cart.ts File
nLet’s start by adding all the required imports.
n
n
import { CartProvider } from "../../providers/cart/cart";nimport firebase from "firebase";n
nAs you can see, I started by importing the CartProvider followed by firebase. We will also be using some variables, so let’s declare them:nn
n
cartItems: any[] = [];n totalAmount: number = 0;n isCartItemLoaded: boolean = false;n isEmptyCart: boolean = true;n
n
n1. cartItems of type array which will hold the items that are added to cart.
n2. totalAmount: of type number which holds the total amount of products in cart.
n3. isCartItemLoaded of type boolean which will help detect if cart items has been loaded.
n4. isEmptyCart of type boolean which will help detect if there are no items in the cart
n
nThe loadCartItems method will be responsible for loading items in cart as the name suggested.
n
n
loadCartItems() {n let loader = this.loadingCtrl.create({n content: "Wait.."n });n loader.present();n this.cartServicen .getCartItems()n .then(val => {n this.cartItems = val;nn if (this.cartItems.length > 0) {n this.cartItems.forEach((v, indx) => {n this.totalAmount += parseInt(v.totalPrice);n });n this.isEmptyCart = false;n }nn this.isCartItemLoaded = true;n loader.dismiss();n })n .catch(err => {});n }n
n
nThe function is pretty simple, we are just making a call to the getCartItems in the CartProvider service, and then sends the returned array of items to the cartItems variable so that we can use it in our cart.html page.
nnn
nnnIt then also check if the returned array has record or not, if there are items in the array we move on to calculate the total amount by looping through the items then set the isEmptyCart variable to false.
n
nThere is also need for buyers to be able to remove item from cart so lets make another method to handle that.
n
n
removeItem(itm) {n this.cartService.removeFromCart(itm).then(() => {n this.loadCartItems();n });n }n
n
nThe method just call the removeFromCart method in our CartProvider service.
n
nThe last method in the .ts file is the checkoout. This will be called when the checkout button is clicked.
n
n
checkOut() {n var user = firebase.auth().currentUser;n if (user) {n this.navCtrl.push("CheckoutPage");n } else {n this.navCtrl.setRoot("LoginPage");n }n }n
n
nIn this method, we took advantage of firebase auth to check if the current user is logged in or not. If logged in it sends user to checkout page if not the user is sent to login page.
n
n
nThe Checkout Page
nThe checkout page is a place where order and payment information will be displayed for a logged in user in other to proceed to making payment. Our checkout page will look like so:
n
n
n
nAs always let’s start by necessary imports for the checkout page.
n
n
import firebase from "firebase";nimport { CartProvider } from "../../providers/cart/cart";nimport { AuthProvider } from "../../providers/auth/auth";nimport { OrderProvider } from "../../providers/order/order";n
n
nAnd all the variables neededn
n
cartItems: any[] = [];n productAmt: number = 0;n totalAmount: number = 0;n shippingFee: number = 20;n customerName: any;n
nWe have imported OrderProvider and AuthProvider that has not been created, let’s create the OrderProvider and AuthProvider like so:n
n
ionic g provider Ordernionic g provider Authn
n
n
n The OrderProvider
nOpen up the OrderProvider and let’s add some codes.
n
nMake reference to firebase orders and orderdetails like so:
n
firedata = firebase.database().ref("/orders");n orderDetails = firebase.database().ref("/ordersdetails");
n
nThe only public method here will be the placeOrder which will be called whenever the place order button is clicked in the checkout page
n
placeOrder(orderObj: any) {n var promise = new Promise((resolve, reject) => {n let orderRef = this.makeid(10);n let orderObject = {n orderRef: orderRef,n customerName: orderObj.name || "",n ShippingAmt: orderObj.shipping,n OrderAmt: orderObj.orderAmount,n totalAmount: orderObj.amountn };nn this.firedata.push(orderObject).then(() => {n orderObj.orders.forEach((v, indx) => {n this.orderDetailsn .push({n orderRef: orderRef,n productName: v.name,n Qty: v.count,n amount: v.totalPricen })n .then(() => {n resolve(true);n });n });n });n });n return promise;n }n
n
nThis method accept order object that will be sent from the checkout page. As you can see, it took care of order and order details. nnnn
nnnThe order object has Order Ref, Custmer Name, Shipping, and Amount while the order details object contains the Order Ref, Product Name, Count and the total amount.nnThere is just one private method that generated order ref.nn
n
makeid(lenght: number) {n var text = "";n var possible =n "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";nn for (var i = 0; i < lenght; i++)n text += possible.charAt(Math.floor(Math.random() * possible.length));nn return text;n }n
n
nThe AuthProvider
nThis service has three methods namely login, registerUser and getuserdetails. The methods names are descriptive enough to explain their roles.nnOpen the AuthProvider and add these three methods like so:nn
n
n login(loginParams){n var promise = new Promise((resolve, reject) => {n firebase.auth().signInWithEmailAndPassword(loginParams.email, loginParams.password).then(() => {n resolve(true);n }).catch((err) => {n reject(err);n })n })nn return promise;n }nn registerUser(userObj: any) {n var promise = new Promise((resolve, reject) => {n firebase .auth().createUserWithEmailAndPassword(userObj.email, userObj.password)n .then(() => {n this.firedata.child(firebase.auth().currentUser.uid).set({n name:userObj.name,n address:userObj.address,n email:userObj.emailn }).then(()=>{n resolve({ success: true });n }).catch((err)=>{n reject(err);n })n // resolve(true);n })n .catch(err => {n reject(err);n });n })n return promise;n }nn getuserdetails() {n var promise = new Promise((resolve, reject) => {n this.firedata.child(firebase.auth().currentUser.uid).once('value', (snapshot) => {n resolve(snapshot.val());n }).catch((err) => {n reject(err);n })n })n return promise;n }n
n
nThe CheckOut.ts File
nNow that we have created the two providers needed in our checkout page let’s now check out the code in the .ts file.
n
nOur first task is to make sure that only logged in users are allowed to get to the checkout page, so we need to check first in the ionicViewWillEnter like so:
n
nionViewWillEnter() {nn var user = firebase.auth().currentUser;nn if (!user) this.navCtrl.setRoot("LoginPage");nn }n
n
n
nOur second task is to display the order information on the page. To achieve this, we will be calling two methods from our providers – getCartItems from cartProvider and getUserDetails from AuthProvider.
n
nn loadCartItems() {n let loader = this.loadingCtrl.create({n content: "Wait.."n });n loader.present();n this.cartService .getCartItems() .then(val => {n this.cartItems = val;n if (this.cartItems.length > 0) {n this.cartItems.forEach((v, indx) => {n this.productAmt += parseInt(v.totalPrice);n });n this.totalAmount = this.productAmt + this.shippingFee;n }n loader.dismiss();n })n .catch(err => {});n }nn ionViewDidLoad() {n this.authServicen .getuserdetails()n .then((response: any) => {n this.customerName = response.name;n })n .catch(err => {n console.log("err", err);n });n }nnn
n
nAnd finally in this checkout.ts file we have the placeOrder method:n
n
nn placeOrder() {n let loader = this.loadingCtrl.create({n content: "Placing Order.."n });n loader.present();n var user = firebase.auth().currentUser;n if (user) {n let orderObj = {n customerId: user.uid,n name: this.customerName,n shipping: this.shippingFee,n orderAmount: this.productAmt,n amount: this.totalAmount,n orders: this.cartItemsn };nn this.orderService.placeOrder(orderObj).then(() => {n loader.dismiss();n this.navCtrl.setRoot('HomePage');n n });n } else {n loader.dismiss();n }n }n
n
nThe SignIn and Register Page
n The signin and register page is required for an existing customer to login in other to complete purchase. The page will look like so:nn
n
n
n
nOpen the login.ts file and replace the code with the following methods:nnnn
n
nnnRegister.ts Filen
n
nn register() {n var userObj = {n name: this.name,n address: this.address,n email: this.email,n password: this.passwordn };nn this.AuthService.registerUser(userObj)n .then((response: any) => {n if (response.success == true) {n this.navCtrl.push('CheckoutPage');n }n })n .catch(err => {n alert(JSON.stringify(err));n });n }nn showLoginPage() {n this.navCtrl.push("LoginPage");n }nn
n
nLogin.ts File
n
login() {n let loader = this.loadingCtrl.create({n content: 'Authenticating..'n });n loader.present();n let loginParams = {n email:this.email,n password:this.passwordn }nn this.authService.login(loginParams).then((res)=>{n loader.dismiss();n this.navCtrl.push('CheckoutPage');n }).catch((err)=>{n loader.dismiss();n this.presentAlert(err.message);n });nnn }nn showRegisterPage() {n this.navCtrl.push("RegisterPage");n }nn presentAlert(message) {n let alert = this.alertCtrl.create({n title: 'Auth Error',n subTitle: message,n buttons: ['Close']n });n alert.present();n }n
nnn
nnnSome more functionalities can be added to this application. But am going to stop here and hopefully this article has helped a lot of people to get started building an ecommerce app using ionicframework.
n
nHappy Coding!
