Using Ember Services to Implement a Cart
Learn to create and implement a cart using Ember services.
We'll cover the following...
A shopping cart is an excellent example of a service. We have products added to our database. However, because the products being bought could belong to multiple categories, the shared state concept of Ember services is particularly useful here.
Creating a service for cart
Let’s create a shopping cart service by running the following Ember CLI command:
ember g service cart-service
This creates a cart-service.js
file in app/services
.
Defining the addToCart
action
In the next step, we need to define the action for the Add to Cart
button in our products-details
component. Let’s open app/components/product-details.hbs
and add an action to the Add to Cart
button:
Press + to interact
{{!-- app/components/product-details.hbs --}}<div class="row pdetails"><div class="col-md-5 col-sm-12"><img class="imgpd img-fluid" src={{@source}} alt="product img"></div><div class="col-md-1 col-sm-0" style="margin-top: 2vh;"></div><div class="col-md-6 col-sm-12"><div class="row"><h2>{{@title}}</h2></div><h6 class="descpd">{{@desc}}</h6><h5 class="pricepd">{{currencysign @price }}</h5><button class="btn btn-success btnpd" type="button" {{action 'addToCart'}} >Add to Cart</button></div></div>
In ...