lundi 13 juin 2022

How to show the quantity we have added instead of showing the item quantity from the database in Ember js?

I have been working on an e-Commerce project. I tried to implement a cart feature in which the data of the product is fetched from the backend. But when I try to display the items in the cart, the quantity of the products from the database are displayed.

I use ember-local-stoage addon to store the id of the product, then with the help of the computed property I fetch the product-details from the database. But I'm unable to store the quantity of the in the inside the local storage as array of hash: [{id: 2, quantity: 3}, {id: 4, quantity: 1}]. But if I try this I'm unable retrieve the id from the array of hash. Due to which the remove method also fails to work. Please someone help me with this issue.

shopping-cart service code:

// app/service/shopping-cart.js

import Service from '@ember/service';
import { computed } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { storageFor } from 'ember-local-storage';
const { service } = Ember.inject;
export default Service.extend({
    session: service('session'),
    store: service('store'),
    currentUser: service('currentUser'),
    itemsIds: storageFor('cart'),

    items:computed("itemsIds.[]", function(){
        const itemsIds = this.itemsIds;
        if(this.get("itemsIds.length") === 0){
            return [];
        }
        else{
            const items = this.store.query('product', {id: this.get("itemsIds.content")});
            return items
        }
    }),
    addItem(itemId){
        console.log(itemId);
        this.get('itemsIds').addObject(parseInt(itemId));
    },
    remove(itemId){
        this.itemsIds.removeObject(parseInt(itemId));
    },
    productPrice: computed.mapBy('items', 'price'),
    totalPrice: computed.sum('productPrice'),

    clear(){
        this.get('itemsIds').clear();
    }

});

cart.hbs template:

<div class="container mt-5">
    <h2>Shopping Cart <i class="fa-solid fa-cart-shopping"></i></h2>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"> Home</li>
            <li class="breadcrumb-item active" aria-current="page">Shopping Cart</li>
        </ol>
    </nav>

    
        <div class="card">
            <div class="card-body">
                <div class="row">
                    <div class="col">
                        <img class="product-image" src="/assests/images/.jpeg" alt="">
                    </div>
                    <div class="col">
                        <h3></h3>
                        <h4><span>Price: </span>Rs </h4>
                        <p>Qty: </p>
                        <button class="btn btn-danger" >Remove Item</button>
                    </div>
                </div>
            </div>
        </div>
        
    

    <section class="w-50 ml-auto mb-5 mt-4">
        <div class="row">
            <span class="col price-title">Total</span>
            <span class="col price-amount">Rs. </span>
        </div>
    </section>
    <button type="button" class="btn btn-success"> Checkout</button>
    <button class="btn btn-warning" >Clear Cart</button>
</div>

products controller(ember) code:

// app/controllers/product.js

import Controller from '@ember/controller';
import { computed } from '@ember/object';
import { getOwner } from '@ember/application';

const { service } = Ember.inject;
export default Controller.extend({
    session: service('session'),
    currentUser: service('currentUser'),
    shoppingCart: service('shoppingCart'),
    quantity: 1,
    price: 0,
    dialogBox: false,
    actions:{
        addToItem(model){
            const id = model.id;
            const quantity = this.quantity;
            this.shoppingCart.addItem(id);
        },

        order(){
            var self = this;
            function setPrice(){
                self.set('price', (self.model.price * self.quantity));
            }
            this.set('dialogBox', true);
            const user_id = this.currentUser.user;
            let date = new Date();
            date.setDate(date.getDate() + 2);
            const orders = this.store.createRecord('order',{
                deliveryDate: date,
                processing: true,
                user_id: user_id
            });
            orders.save().then(setPrice());
        },

        orderItem(){
            this.set('dialogBox', false);
            console.log(this.model.id);
            const orderItems = this.store.createRecord('order-item', {
               quantity: this.quantity,
               product_id: this.model,
               price: this.quantity * this.model.price

           })
           orderItems.save().then(function(response){
               alert("Order has been placed successfully!!");
           });
        },

        showDialog(){
            this.set('dialogBox', true);
        },

        hideDialog(){
            this.set('dialogBox', false);
        },
        cancel(){
            
        }
    }
});

products controller(ruby on rails):

class ProductsController < ApplicationController
    def index
        if params[:id]
            render json: Product.find(params[:id]) 
        else
            render json: Product.all 
        end
        
    end

    def show
        render json: Product.find(params[:id])
    end
    def create
        title = params[:product][:title]
        description = params[:product][:description]
        price = params[:product][:price]
        quantity = params[:product][:quantity]

        Product.create!(
            title: title,
            description: description,
            price: price,
            quantity: quantity,
        )

    end
end

product.hbs


<div class="container mt-5">
    <div class="row">
        <div class="col">
             <i class="fa-solid fa-arrow-left fa-2x"></i>
        </div>
        <div class="col">
            <h1>Product details</h1>
        </div>
        <div class="col">
            
                <i class="fa-solid fa-cart-shopping fa-2x">
                
                    <span class="cart-items-count-product d-inline-flex justify-content-center align-items-center">
                        
                    </span>
                
            </i>
        </div>
    </div>
    <hr>
    <div class="container">
        <div class="row">
            <div class="col-sm-6">
                <img class="product-image" src="/assests/images/.jpeg" alt="">
            </div>

            <div class="col-sm-6">
                <h1></h1>
                
                <button class="btn btn-success"  >
                    <i class="fa-solid fa-cart-shopping"></i>
                    <span>Add to Cart</span>
                </button>
                <label class="quantity-label" for="quantity">Quantity Selector:</label>
                "> --}}
                
            </div>
        </div>
    </div> 
    <hr> 
    <h4> Description</h4>
    <div class="container">
        
            <p></p>
        
        <ul>
        
        </ul>
    </div>
    <button class="btn btn-success" >Order now</button>

</div>

<div class="dialog-container ">
    <div class="dialog">
        <h5></h5>
        <h5>The price is </h5>
        <h5 class="confirmation">Are you sure, you wanna place this order?</h5>
        <h5>Quantity: </h5>
        <div class="dialog-buttons">
            <button  class="btn btn-success">
                <i class="fa-solid fa-badge-check"></i>Yes
            </button>
            <button  class="btn btn-danger">Cancel</button>
        </div>
    </div>
</div>



Aucun commentaire:

Enregistrer un commentaire