After the docs UI redesign `h2` tags got a border top. `border-top: 1px solid #dbdbdb;`; In the sections of Getting Started guide in order to separate `What's next` from above content an `<hr />` tag was used, that now becomes unnecessary. This commit removes unnecessary `<hr />` tags. PR Close #40693
15 KiB
Managing data
This guide builds on the second step of the Getting started with a basic Angular application tutorial, Adding navigation. At this stage of development, the 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 step of the tutorial guides you through creating a shopping cart in the following phases:
- Update the product details view 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
HttpClientto retrieve shipping data from a.jsonfile.
{@a create-cart-service}
Create the shopping cart service
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.
Currently, users can view product information, and the application can simulate sharing and notifications about product changes.
The next step is to build a way for users to add products to a cart. This section walks you through adding a Buy button and setting up a cart service to store information about products in the cart.
{@a generate-cart-service}
Define a cart service
-
To generate a cart service, right click on the
appfolder, choose Angular Generator, and choose Service. Name the new servicecart. -
In the
CartServiceclass, define anitemsproperty 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, which empties the cart.
-
{@a product-details-use-cart-service}
Use the cart service
This section walks you through using the CartService to add a product to the cart.
-
In
product-details.component.ts, 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:- Takes the current
productas an argument. - Uses the
CartServiceaddToCart()method to add the product to the cart. - Displays a message that you've added a product to the cart.
- Takes the current
-
In
product-details.component.html, add a button with the label Buy, and bind theclick()event to theaddToCart()method. This code updates the product details template with a Buy button that adds the current product to the cart. -
Verify that the new Buy button appears as expected by refreshing the application and clicking 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 view
For customers to see their cart, you can create the cart view in two steps:
- Create a cart component and configure routing to the new component.
- Display the cart items.
Set up the cart component
To create the cart view, follow the same steps you did to create the ProductDetailsComponent and configure routing for the new component.
-
Generate a cart component named
cartby right-clicking theappfolder, choosing Angular Generator, and Component.StackBlitz also generates an
ngOnInit()by default in components. You can ignore theCartComponentngOnInit()for this tutorial. -
Open
app.module.tsand add a route for the componentCartComponent, with apathofcart. -
Update the Checkout button so that it routes to the
/cartURL. Intop-bar.component.html, add arouterLinkdirective pointing to/cart. -
Verify the new
CartComponentworks as expected by clicking the Checkout button. You can see the "cart works!" default text, and the URL has the patternhttps://getting-started.stackblitz.io/cart, wheregetting-started.stackblitz.iomay be different for your StackBlitz project.
Display the cart items
This section shows you how to use the cart service to display the products in the cart.
-
In
cart.component.ts, import theCartServicefrom thecart.service.tsfile. -
Inject the
CartServiceso that theCartComponentcan use it by adding it to theconstructor(). -
Define the
itemsproperty to store the products in the cart.This code sets the items using the
CartServicegetItems()method. You defined this method when you createdcart.service.ts. -
Update the cart template with a header, and use a
<div>with an*ngForto display each of the cart items with its name and price. The resultingCartComponenttemplate is as follows. -
Verify that your cart works as expected:
- Click My Store
- Click on a product name to display its details.
- Click Buy to add the product to the cart.
- Click Checkout to see 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.
Angular HttpClient is a built-in way to fetch data from external APIs and provide them to your application as a stream.
This section shows you how to use HttpClient to retrieve shipping prices from an external file.
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.
Configure AppModule to use HttpClient
To use Angular's HttpClient, you must configure your application to use HttpClientModule.
Angular's HttpClientModule registers the providers your application needs to use the HttpClient service throughout your application.
-
In
app.module.ts, importHttpClientModulefrom the@angular/common/httppackage 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. -
To register Angular's
HttpClientproviders globally, addHttpClientModuleto theAppModule@NgModule()importsarray.
Configure CartService to use HttpClient
The next step is to inject the HttpClient service into your service so your application can fetch data and interact with external APIs and resources.
-
In
cart.service.ts, importHttpClientfrom the@angular/common/httppackage. -
Inject
HttpClientinto theCartServiceconstructor().
Configure CartService to get shipping prices
To get shipping data, from shipping.json, You can use the HttpClient get() method.
-
In
cart.service.ts, below theclearCart()method, define a newgetShippingPrices()method that uses theHttpClientget()method.
For more information about Angular's HttpClient, see the Client-Server Interaction guide.
Create a shipping component
Now that you've configured your application to retrieve shipping data, you can create a place to render that data.
-
Generate a new component named
shippingby right-clicking theappfolder, choosing Angular Generator, and selecting Component. -
In
app.module.ts, add a route for shipping. Specify apathofshippingand 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/shippingwhere thegetting-started.stackblitz.iopart may be different for your StackBlitz project.
Configuring the ShippingComponent to use CartService
This section guides you through modifying the ShippingComponent to retrieve shipping data via HTTP from the shipping.json file.
-
In
shipping.component.ts, importCartService. -
Inject the cart service in the
ShippingComponentconstructor(). -
Define a
shippingCostsproperty that sets theshippingCostsproperty using thegetShippingPrices()method from theCartService. -
Update the
ShippingComponenttemplate to display the shipping types and prices using theasyncpipe.The
asyncpipe 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, theasyncpipe automatically stops. For detailed information about theasyncpipe, see the AsyncPipe API documentation. -
Add a link from the
CartComponentview to theShippingComponentview. -
Click the Checkout button to see the updated cart. Remember that changing the application causes the preview to refresh, which empties the cart.
Click on the link to navigate to the shipping prices.
What's next
You now have a store application with a product catalog, a shopping cart, and you can look up shipping prices.
To continue exploring Angular:
- Continue to Forms for User Input to finish the application by adding the shopping cart view and a checkout form.
- Skip ahead to Deployment to move to local development, or deploy your application to Firebase or your own server.





