...

/

Updating the Count of Products in Cart

Updating the Count of Products in Cart

Learn to update product count in the cart using a service.

We need to specify the number of products in the cart. This functionality can be implemented by updating cart-service.

Updating the cart-service file

Let’s open the app/services/cart-service.js file and add the required functionality:

Press + to interact
//app/services/cart-service.js
import Service from '@ember/service';
import { tracked } from '@glimmer/tracking';
class Product {
@tracked count;
product_id;
title;
desc;
source;
price;
constructor(product) {
this.product_id = product.product_id;
this.count = product.count;
this.title = product.title;
this.desc = product.desc;
this.source = product.source;
this.price = product.price;
this.total = product.total;
}
}
export default class CartServiceService extends Service {
@tracked productsList = [];
addProduct(product) {
const existingProduct = this.productsList.find(({ product_id }) => {
return product_id == product.product_id
});
if (existingProduct) {
existingProduct.count += 1;
existingProduct.total = existingProduct.price* existingProduct.count;
}
else {
this.productsList = [
...this.productsList,
new Product({
...product,
count: 1,
total : product.price
}),
];
}
}
}
  • Lines 4–20: We create a class named Product and initialize all the values:
    • Line 5: We create a tracked property named
...