Requirement: I clicked the “Buy” button on a product detail page and successfully added the product to the cart, but the cart page was not displayed. This article implements the display page of the shopping cart.

In app.module.ts, add a route to the Cart View:

Add route to cart Component in the checkout button of the Top bar Component:

The code highlighted in red is new:

Test: Before clicking Checkout, note the URL in the address bar:

After clicking:

Now display the contents of the cart in the Cart Component. Inject the Cart Service into the Cart Component via constructor injection:

Define the Items property to store the data displayed on the Cart Component View:

When the Cart View is displayed, call the Cart Service to assign the items property:

this.items = this.cartService.getItems();

In the Cart Component template, display the contents of the items property in turn:

<h3>Cart</h3>

<div class="cart-item" *ngFor="let item of items">
  <span>{{ item.name }}</span>
  <span>{{ item.price | currency }}</span>
</div>
Copy the code

Test: Select two products, go to the detail page, click Buy button, click checkout, route to the cart page, and these two products already appear in the Cart Component view:

For more of Jerry’s original articles, please follow the public account “Wang Zixi “: