Search⌘ K
AI Features

Updating the Count of Products in Cart

Understand how to implement product count updates within an Ember.js cart service. This lesson guides you through modifying the cart-service file to track product counts and totals, and updating the cart template to display these changes dynamically. You’ll learn to manage product quantities using Ember's reactive properties and service injection for state sharing across the app.

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:

Javascript (babel-node)
//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
...