17 KiB
Getting Started with Angular: Managing Data
At the end of Routing, the online store application has a product catalog with two views: a product list and product details. Users can click on a product name from the list to see details in a new view, with a distinct URL, or route.
This page guides you through creating the shopping cart in three phases:
- Update the product details page to include a "Buy" button, which adds the current product to a list of products that a cart service manages.
- Add a cart component, which displays the items in the cart.
- Add a shipping component, which retrieves shipping prices for the items in the cart by using Angular's
HttpClient
to retrieve shipping data from a.json
file.
{@a services}
Services
Services are an integral part of Angular applications. In Angular, a service is an instance of a class that you can make available to any part of your application using Angular's dependency injection system.
Services are the place where you share data between parts of your application. For the online store, the cart service is where you store your cart data and methods.
{@a create-cart-service}
Create the shopping cart service
Up to this point, users can view product information, and simulate sharing and being notified about product changes. They cannot, however, buy products.
In this section, you add a "Buy" button to the product details page and set up a cart service to store information about products in the cart.
Later, the Forms part of this tutorial guides you through accessing this cart service from the page where the user checks out.
{@a generate-cart-service}
Define a cart service
-
Generate a cart service.
-
Right click on the
app
folder, chooseAngular Generator
, and chooseService
. Name the new servicecart
. -
StackBlitz might generate the
@Injectable()
decorator without the{ providedIn: 'root' }
statement as above. Instead, the generator provides the cart service inapp.module.ts
by default. For the purposes of this tutorial, either way works. The@Injectable()
{ providedIn: 'root' }
syntax allows tree shaking, which is beyond the scope of this guide.
-
-
In the
CartService
class, define anitems
property to store the array of the current products in the cart. -
Define methods to add items to the cart, return cart items, and clear the cart items:
-
The
addToCart()
method appends a product to an array ofitems
. -
The
getItems()
method collects the items users add to the cart and returns each item with its associated quantity. -
The
clearCart()
method returns an empty array of items.
-
{@a product-details-use-cart-service}
Use the cart service
This section walks you through using the cart service to add a product to the cart with a "Buy" button.
-
Open
product-details.component.ts
. -
Configure the component to use the cart service.
-
Import the cart service.
-
Inject the cart service by adding it to the
constructor()
.
-
-
Define the
addToCart()
method, which adds the current product to the cart.The
addToCart()
method does the following three things:- Receives the current
product
. - Uses the cart service's
addToCart()
method to add the product the cart. - Displays a message that you've added a product to the cart.
- Receives the current
-
Update the product details template with a "Buy" button that adds the current product to the cart.
-
Open
product-details.component.html
. -
Add a button with the label "Buy", and bind the
click()
event to theaddToCart()
method:
The line,
<h4>{{ product.price | currency }}</h4>
uses thecurrency
pipe to transformproduct.price
from a number to a currency string. A pipe is a way you can transform data in your HTML template. For more information about Angular pipes, see Pipes. -
-
To see the new "Buy" button, refresh the application and click on a product's name to display its details.
-
Click the "Buy" button to add the product to the stored list of items in the cart and display a confirmation message.
Create the cart page
At this point, users can put items in the cart by clicking "Buy", but they can't yet see their cart.
Create the cart page in two steps:
- Create a cart component and configure routing to the new component. At this point, the cart page will only have default text.
- Display the cart items.
Set up the component
To create the cart page, begin by following the same steps you did to create the product details component and configure routing for the new component.
-
Generate a cart component, named
cart
.Reminder: In the file list, right-click the
app
folder, chooseAngular Generator
andComponent
. -
Add routing (a URL pattern) for the cart component.
Open
app.module.ts
and add a route for the componentCartComponent
, with apath
ofcart
: -
Update the "Checkout" button so that it routes to the
/cart
url.Open
top-bar.component.html
and add arouterLink
directive pointing to/cart
. -
To see the new cart component, click the "Checkout" button. You can see the "cart works!" default text, and the URL has the pattern
https://getting-started.stackblitz.io/cart
, wheregetting-started.stackblitz.io
may be different for your StackBlitz project.
Display the cart items
You can use services to share data across components:
- The product details component already uses the cart service to add products to the cart.
- This section shows you how to use the cart service to display the products in the cart.
-
Open
cart.component.ts
. -
Configure the component to use the cart service.
-
Import the
CartService
from thecart.service.ts
file. -
Inject the
CartService
so that the cart component can use it.
-
-
Define the
items
property to store the products in the cart. -
Set the items using the cart service's
getItems()
method. Recall that you defined this method when you generatedcart.service.ts
.The resulting
CartComponent
class is as follows: -
Update the template with a header, and use a
<div>
with an*ngFor
to display each of the cart items with its name and price.The resulting
CartComponent
template is as follows: -
Test your cart component.
- Click on "My Store" to go to the product list page.
- Click on a product name to display its details.
- Click "Buy" to add the product to the cart.
- Click "Checkout" to see the cart.
- To add another product, click "My Store" to return to the product list.
Repeat to add more items to the cart.
<div class="lightbox">
<img src='generated/images/guide/start/cart-page-full.png' alt="Cart page with products added">
</div>
StackBlitz tip: Any time the preview refreshes, the cart is cleared. If you make changes to the app, the page refreshes, so you'll need to buy products again to populate the cart.
For more information about services, see Introduction to Services and Dependency Injection.
Retrieve shipping prices
Servers often return data in the form of a stream.
Streams are useful because they make it easy to transform the returned data and make modifications to the way you request that data.
The Angular HTTP client, HttpClient
, is a built-in way to fetch data from external APIs and provide them to your app as a stream.
This section shows you how to use the HTTP client to retrieve shipping prices from an external file.
Predefined shipping data
The application that StackBlitz generates for this guide comes with predefined shipping data in assets/shipping.json
.
Use this data to add shipping prices for items in the cart.
Use HttpClient
in the AppModule
Before you can use Angular's HTTP client, you must configure your app to use HttpClientModule
.
Angular's HttpClientModule
registers the providers your app needs to use a single instance of the HttpClient
service throughout your app.
- Open
app.module.ts
.
This file contains imports and functionality that is available to the entire app.
-
Import
HttpClientModule
from the@angular/common/http
package at the top of the file with the other imports. As there are a number of other imports, this code snippet omits them for brevity. Be sure to leave the existing imports in place. -
Add
HttpClientModule
to theAppModule
@NgModule()
imports
array to register Angular'sHttpClient
providers globally.
Use HttpClient
in the cart service
Now that the AppModule
imports the HttpClientModule
, the next step is to inject the HttpClient
service into your service so your app can fetch data and interact with external APIs and resources.
-
Open
cart.service.ts
. -
Import
HttpClient
from the@angular/common/http
package. -
Inject
HttpClient
into theCartService
constructor:
Define the get()
method
Multiple components can leverage the same service.
Later in this tutorial, the shipping component uses the cart service to retrieve shipping data via HTTP from the shipping.json
file.
First, define a get()
method.
-
Continue working in
cart.service.ts
. -
Below the
clearCart()
method, define a newgetShippingPrices()
method that uses theHttpClient
get()
method to retrieve the shipping data.
For more information about Angular's HttpClient
, see HttpClient.
Define the shipping page
Now that your app can retrieve shipping data, create a shipping component and template.
-
Generate a new component named
shipping
.Reminder: In the file list, right-click the
app
folder, chooseAngular Generator
andComponent
. -
In
app.module.ts
, add a route for shipping. Specify apath
ofshipping
and a component ofShippingComponent
.There's no link to the new shipping component yet, but you can see its template in the preview pane by entering the URL its route specifies. The URL has the pattern:
https://getting-started.stackblitz.io/shipping
where thegetting-started.stackblitz.io
part may be different for your StackBlitz project. -
Modify the shipping component so that it uses the cart service to retrieve shipping data via HTTP from the
shipping.json
file.-
Import the cart service.
-
Define a
shippingCosts
property. -
Inject the cart service in the
ShippingComponent
constructor: -
Set the
shippingCosts
property using thegetShippingPrices()
method from the cart service.
-
-
Update the shipping component's template to display the shipping types and prices using the
async
pipe:The
async
pipe returns the latest value from a stream of data and continues to do so for the life of a given component. When Angular destroys that component, theasync
pipe automatically stops. For detailed information about theasync
pipe, see the AsyncPipe API documentation. -
Add a link from the cart page to the shipping page:
-
Test your shipping prices feature:
Click the "Checkout" button to see the updated cart. Remember that changing the app causes the preview to refresh, which empties the cart.
Click on the link to navigate to the shipping prices.
Next steps
Congratulations! You have an online store application with a product catalog and shopping cart. You can also look up and display shipping prices.
To continue exploring Angular, choose either of the following options:
- Continue to the "Forms" section to finish the app by adding the shopping cart page and a checkout form.
- Skip ahead to the "Deployment" section to move to local development, or deploy your app to Firebase or your own server.