# Conflicts: # aio/content/cli/index.md # aio/content/guide/accessibility.md # aio/content/guide/ajs-quick-reference.md # aio/content/guide/angular-compiler-options.md # aio/content/guide/animations.md # aio/content/guide/aot-compiler.md # aio/content/guide/architecture-components.md # aio/content/guide/architecture-modules.md # aio/content/guide/architecture-next-steps.md # aio/content/guide/architecture-services.md # aio/content/guide/attribute-directives.md # aio/content/guide/bootstrapping.md # aio/content/guide/browser-support.md # aio/content/guide/cli-builder.md # aio/content/guide/comparing-observables.md # aio/content/guide/component-styles.md # aio/content/guide/creating-libraries.md # aio/content/guide/dependency-injection-in-action.md # aio/content/guide/dependency-injection-navtree.md # aio/content/guide/dependency-injection-providers.md # aio/content/guide/dependency-injection.md # aio/content/guide/deployment.md # aio/content/guide/deprecations.md # aio/content/guide/displaying-data.md # aio/content/guide/dynamic-component-loader.md # aio/content/guide/elements.md # aio/content/guide/file-structure.md # aio/content/guide/glossary.md # aio/content/guide/http.md # aio/content/guide/i18n.md # aio/content/guide/ivy-compatibility.md # aio/content/guide/language-service.md # aio/content/guide/lifecycle-hooks.md # aio/content/guide/module-types.md # aio/content/guide/ngmodule-faq.md # aio/content/guide/ngmodule-vs-jsmodule.md # aio/content/guide/ngmodules.md # aio/content/guide/observables-in-angular.md # aio/content/guide/pipes.md # aio/content/guide/providers.md # aio/content/guide/releases.md # aio/content/guide/route-animations.md # aio/content/guide/router-tutorial.md # aio/content/guide/router.md # aio/content/guide/rx-library.md # aio/content/guide/schematics-authoring.md # aio/content/guide/schematics-for-libraries.md # aio/content/guide/service-worker-config.md # aio/content/guide/service-worker-getting-started.md # aio/content/guide/structural-directives.md # aio/content/guide/styleguide.md # aio/content/guide/template-syntax.md # aio/content/guide/template-typecheck.md # aio/content/guide/testing.md # aio/content/guide/typescript-configuration.md # aio/content/guide/upgrade-setup.md # aio/content/guide/user-input.md # aio/content/guide/using-libraries.md # aio/content/guide/web-worker.md # aio/content/guide/workspace-config.md # aio/content/marketing/docs.md # aio/content/marketing/events.html # aio/content/navigation.json # aio/content/start/index.md # aio/content/start/start-data.md # aio/content/start/start-deployment.md # aio/content/tutorial/toh-pt2.md # aio/content/tutorial/toh-pt4.md # aio/package.json # aio/src/app/app.component.ts # aio/src/app/layout/footer/footer.component.html # aio/src/app/shared/custom-icon-registry.ts # aio/src/environments/environment.stable.ts # aio/tools/stackblitz-builder/builder.js # aio/tools/transforms/angular-content-package/index.js # aio/tools/transforms/templates/api/lib/memberHelpers.html # aio/yarn.lock # integration/ng_elements/e2e/app.e2e-spec.ts # integration/ng_elements/src/app.ts # packages/common/src/pipes/date_pipe.ts # packages/core/src/metadata/directives.ts # packages/core/src/metadata/ng_module.ts # packages/core/src/render/api.ts # packages/forms/src/directives/ng_model.ts # packages/forms/src/form_builder.ts # packages/forms/src/model.ts # packages/platform-browser/src/browser.ts # packages/router/src/config.ts # packages/router/src/directives/router_link.ts # packages/router/src/directives/router_link_active.ts # packages/router/src/events.ts # packages/router/src/router.ts # packages/router/src/router_module.ts # packages/router/src/router_state.ts
23 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.
本章基于以一个基本 Anguluar 应用快速上手的第二步 —— 添加导航。 在此开发阶段,本商店应用具有一个包含两个视图的商品名录:商品列表和商品详情。用户点击清单中的某个商品名称,就会在新视图中看到具有专门的 URL 或路由的详情页。
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.
修改商品详情视图,让它包含一个 “Buy” 按钮,它会把当前商品添加到由 "购物车服务" 管理的商品列表中。
-
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.添加一个配送组件,它会使用 Angular 的
HttpClient从.json文件中检索配送数据来取得购物车中这些商品的运费。
{@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.要想生成购物车服务,请右键单击
app文件夹,选择Angular Generator,并选择Service。把这个新服务命名为cart。
-
In the
CartServiceclass, define anitemsproperty to store the array of the current products in the cart.在
CartService类中,定义一个items属性来把当前商品的数组存储在购物车中。 -
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.addToCart()方法会将产品附加到items数组中。-
The
getItems()method collects the items users add to the cart and returns each item with its associated quantity.getItems()方法会收集用户加到购物车中的商品,并返回每个商品及其数量。 -
The
clearCart()method returns an empty array of items, which empties the cart.clearCart()方法返回一个空数组。
-
{@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.
本节会教你使用 CartService 来把一个商品添加到购物车中。
-
In
product-details.component.ts, import the cart service.在
product-details.component.ts中导入购物车服务。-
Inject the cart service by adding it to the
constructor().通过把购物车服务注入到这里的
constructor()中来注入它。
-
-
Define the
addToCart()method, which adds the current product to the cart.定义
addToCart()方法,该方法会当前商品添加到购物车中。The
addToCart()method does the following:- Takes the current
productas an argument. - Uses the
CartServiceaddToCart()method to add the product 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.The line,
<h4>{{ product.price | currency }}</h4>, uses thecurrencypipe to transformproduct.pricefrom 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.<h4>{{ product.price | currency }}</h4>这一行使用了currency管道将product.price从数字转换为货币字符串。管道是一种可以在 HTML 模板中转换数据的方法。关于 Angular 管道的更多信息,参阅管道。 -
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.
点击“Buy”按钮来把该商品添加到购物车中存储的商品列表中,并显示一条确认消息。
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.右键单击
app文件夹,选择 Angular Generator 和 Component 以生成一个名为cart的购物车组件。 -
Open
app.module.tsand add a route for the componentCartComponent, with apathofcart.打开
app.module.ts,为组件CartComponent添加一个路由,其路由为cart: -
Update the Checkout button so that it routes to the
/cartURL. Intop-bar.component.html, add arouterLinkdirective pointing to/cart.修改 "Checkout" 按钮,以便让它路由到
/cart。 在top-bar.component.html中添加一个指向/cart的routerLink指令。 -
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.要查看新的购物车组件,请点击“Checkout”按钮。你会看到默认文本“cart works!”,该 URL 的格式为
https://getting-started.stackblitz.io/cart,其中的 getting-started.stackblitz.io 部分可能与你的 StackBlitz 项目不同。
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.在
cart.component.ts中,从cart.service.ts文件中导入CartService。-
Inject the
CartServiceso that theCartComponentcan use it by adding it to theconstructor().注入
CartService,以便购物车组件可以使用它。
-
-
Define the
itemsproperty to store the products in the cart.定义
items属性,以便把商品存放在购物车中。 -
Set the items using the
CartServicegetItems()method. You defined this method when you createdcart.service.ts. By using thegetItems()method in Angular'sngOnInit(), Angular usesgetItems()upon initialization ofCartComponent. 使用购物车服务的getItems()方法设置这些商品。回想一下,你在生成cart.service.ts时定义过这个方法。The resulting
CartComponentclass is as follows.所生成的
CartComponent类是这样的: -
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. 修改模板,加上标题,用带有*ngFor的<div>来显示每个购物车商品的名字和价格。The resulting
CartComponenttemplate is as follows.生成的
CartComponent模板如下: -
Verify that your cart works as expected:
验证你的购物车如预期般工作:
-
Click My Store
点击 My Store
-
Click on a product name to display its details.
单击商品名称以显示其详细信息。
-
Click Buy to add the product to the cart.
点击Buy 将商品添加到购物车。
-
Click Checkout to see the cart.
点击Checkout查看购物车。
-
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.
服务器通常采用流的形式返回数据。
流是很有用的,因为它们可以很容易地转换返回的数据,也可以修改你请求数据的方式。
Angular 的 HTTP 客户端( HttpClient )是一种内置的方式,可以从外部 API 中获取数据,并以流的形式提供给你的应用。
This section shows you how to use HttpClient to retrieve shipping prices from an external file.
本节会为你展示如何使用 HttpClient 从外部文件中检索运费。
预定义的配送数据
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.
在本指南的 StackBlitz 应用中,通过 assets/shipping.json 文件提供了一些预定义的配送数据。你可以利用这些数据为购物车中的商品添加运费。
Configure AppModule to use HttpClient
To use Angular's HttpClient, you must configure your application to use HttpClientModule.
要使用 Angular 的 HTTP 客户端之前,你必须先配置你的应用来使用 HttpClientModule。
Angular's HttpClientModule registers the providers your application needs to use the HttpClient service throughout your application.
Angular 的 HttpClientModule 中注册了在整个应用中使用 HttpClient 服务的单个实例所需的服务提供者。
-
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.在
app.module.ts的顶部从@angular/common/http包中导入HttpClientModule以及其它导入项。 由于有很多其它导入项,因此这里的代码片段省略它们,以保持简洁。请确保现有的导入都还在原地。 -
To register Angular's
HttpClientproviders globally, addHttpClientModuleto theAppModule@NgModule()importsarray.把
HttpClientModule添加到AppModule@NgModule()的imports数组中,以便全局注册 Angular 的HttpClient。
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.从
@angular/common/http包中导入HttpClient。 -
Inject
HttpClientinto theCartServiceconstructor().把
HttpClient注入到CartService的构造函数中:
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.在
cart.service.ts中clearCart()方法下面,定义一个新的getShippingPrices()方法,该方法会调用HttpClient#get()方法。
For more information about Angular's HttpClient, see the Client-Server Interaction guide.
要了解关于 Angular HttpClient 的更多信息,请参阅客户端-服务器集成指南。
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.右键单击
app文件夹,选择 Angular Generator 和 Component 来生成一个名为shipping的新组件。 -
In
app.module.ts, add a route for shipping. Specify apathofshippingand a component ofShippingComponent.在
app.module.ts中,添加一个配送路由。其path为shipping,其 component 为ShippingComponent。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.新的配送组件尚未链接到任何其它组件,但你可以通过输入其路由指定的 URL 在预览窗格中看到它的模板。该 URL 具有以下模式:
https://getting-started.stackblitz.io/shipping,其中的 gets-started.stackblitz.io 部分可能与你的 StackBlitz 项目不同。
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.-
Define a
shippingCostsproperty.定义
shippingCosts属性。 -
Inject the cart service in the
ShippingComponentconstructor().把购物车服务注入到
ShippingComponent的构造函数中: -
Set the
shippingCostsproperty using thegetShippingPrices()method from theCartService.利用购物车服务的
getShippingPrices()方法设置shippingCosts属性。
-
-
Update the
ShippingComponenttemplate to display the shipping types and prices using theasyncpipe.利用
async管道修改配送组件的模板,以显示配送类型和价格: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.async管道从数据流中返回最新值,并在所属组件的生命期内持续返回。当 Angular 销毁该组件时,async管道会自动停止。关于async管道的详细信息,请参阅 AsyncPipe API 文档。 -
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.
点击 Checkout 按钮,查看更新后的购物车。注意,修改本应用会导致预览窗格刷新,这会清空购物车。
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:
要继续探索 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.
跳到部署部分来转为本地开发,或者把你的应用部署到 Firebase 或你自己的服务器上。





