新聞中心
管理數(shù)據(jù)
本章基于以一個基本 Angular 應用快速上手的第二步 —— 添加導航。 在此開發(fā)階段,本商店應用具有一個包含兩個視圖的商品名錄:商品列表和商品詳情。用戶點擊清單中的某個商品名稱,就會在新視圖中看到具有專門的 URL 或路由的詳情頁。

創(chuàng)新互聯(lián)是一家專注網站建設、網絡營銷策劃、小程序制作、電子商務建設、網絡推廣、移動互聯(lián)開發(fā)、研究、服務為一體的技術型公司。公司成立10多年以來,已經為超過千家成都服務器托管各業(yè)的企業(yè)公司提供互聯(lián)網服務。現(xiàn)在,服務的超過千家客戶與我們一路同行,見證我們的成長;未來,我們一起分享成功的喜悅。
本頁將指導你分三個步驟創(chuàng)建購物車:
- 修改商品詳情視圖,讓它包含一個 “Buy” 按鈕,它會把當前商品添加到由 "購物車服務" 管理的商品列表中。
- 添加一個購物車組件,它會顯示購物車中的商品。
- 添加一個配送組件,它會使用 Angular 的 ?
HttpClient?從 ?.json? 文件中檢索配送數(shù)據(jù)來取得購物車中這些商品的運費。
創(chuàng)建購物車服務
在 Angular 中, 服務是類的一個實例, 借助 Angular 的依賴注入體系,你可以在應用中的任意部分使用它。
現(xiàn)在, 用戶可以瀏覽產品信息,而應用可以模擬分享產品,以及發(fā)出產品變更通知。
下一步是為用戶提供一種把產品添加到購物車中的方法。 本章節(jié)將帶領你添加一個 Buy 按鈕并且建立一個購物車服務以保存購物車中的產品信息。
定義購物車服務
本節(jié)將引導你創(chuàng)建用于跟蹤添加到購物車的產品的 ?CartService ?。
- 在終端中通過運行以下命令生成一個新的 ?
cart?服務: - 將 ?
Product?接口從 ?./products.ts? 導入到 ?cart.service.ts? 文件中,在 ?CartService?類中,定義一個 ?items?屬性來存儲購物車中當前產品的數(shù)組。 - 定義把商品添加到購物車、返回購物車商品以及清除購物車商品的方法:
- ?
addToCart()? 方法會將產品附加到 ?items?數(shù)組中。 - ?
getItems()? 方法會收集用戶加到購物車中的商品,并返回每個商品及其數(shù)量。 - ?
clearCart()? 方法返回一個空數(shù)組。
ng generate service cartimport { Product } from './products';
/* . . . */
export class CartService {
items: Product[] = [];
/* . . . */
}export class CartService {
items: Product[] = [];
/* . . . */
addToCart(product: Product) {
this.items.push(product);
}
getItems() {
return this.items;
}
clearCart() {
this.items = [];
return this.items;
}
/* . . . */
}使用購物車服務
本節(jié)會教你使用 ?CartService ?來把一個商品添加到購物車中。
- 在 ?
product-details.component.ts? 中導入購物車服務。 - 通過把購物車服務注入到這里的 ?
constructor()? 中來注入它。 - 定義 ?
addToCart()? 方法,該方法會當前商品添加到購物車中。 - 以當前'product'作為參數(shù)。
- 使用 ?
CartService??addToCart()? 方法去添加產品到購物車中。 - 顯示一條你已經添加了一個產品到購物車到消息。
- 在 ?
product-details.component.html? 中,添加一個帶有 Buy 標簽的按鈕,并且把其 ?click()? 事件綁定到 ?addToCart()? 方法上。 這段代碼會為產品詳情模板添加一個 Buy 按鈕,并把當前產品添加到購物車中。 - 刷新應用,以驗證新的 ?
Buy?按鈕如預期般出現(xiàn)了,并且單擊某個產品的名稱,以展示其詳情。 - 點擊“Buy”按鈕來把該商品添加到購物車中存儲的商品列表中,并顯示一條確認消息。
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Product, products } from '../products';
import { CartService } from '../cart.service';export class ProductDetailsComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private cartService: CartService
) { }
}
export class ProductDetailsComponent implements OnInit {
addToCart(product: Product) {
this.cartService.addToCart(product);
window.alert('Your product has been added to the cart!');
}
}?addToCart()? 方法做了如下事情:
Product Details
{{ product.name }}
{{ product.price | currency }}
{{ product.description }}
創(chuàng)建購物車視圖
為了讓顧客看到他們的購物車,你可以用兩步創(chuàng)建購物車視圖:
- 創(chuàng)建一個購物車組件并配置指向這個新組件的路由。
- 顯示購物車商品
設置該組件
要創(chuàng)建購物車視圖,可遵循與創(chuàng)建 ?ProductDetailsComponent ?相同的步驟,并且為這個新組件配置路由。
- 通過運行以下命令在終端中生成一個名為 ?
cart?的新組件: - 請注意,新創(chuàng)建的 ?
CartComponent? 已添加到 ?app.module.ts? 中模塊的 ?declarations?中。 - 打開 ?
app.module.ts?,為組件 ?CartComponent?添加一個路由,其路由為 ?cart?: - 修改 "Checkout" 按鈕,以便讓它路由到 ?
/cart?。 在 ?top-bar.component.html? 中添加一個指向 ?/cart? 的 ?routerLink?指令。 - 要查看新的購物車組件,請點擊“Checkout”按鈕。你會看到默認文本“cart works!”,該 URL 的格式為 ?
https://getting-started.stackblitz.io/cart?,其中的 getting-started.stackblitz.io 部分可能與你的 StackBlitz 項目不同。
ng generate component cart此命令將生成 ?cart.component.ts? 文件及其關聯(lián)的模板和樣式文件。
import { Component } from '@angular/core';
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.css']
})
export class CartComponent {
constructor() { }
}StackBlitz 還在組件中默認生成一個 ?ngOnInit()? 。對于本教程,你可以忽略 ?CartComponent ?的 ?ngOnInit()? 。
import { CartComponent } from './cart/cart.component';
@NgModule({
declarations: [
AppComponent,
TopBarComponent,
ProductListComponent,
ProductAlertsComponent,
ProductDetailsComponent,
CartComponent,
],@NgModule({
imports: [
BrowserModule,
ReactiveFormsModule,
RouterModule.forRoot([
{ path: '', component: ProductListComponent },
{ path: 'products/:productId', component: ProductDetailsComponent },
{ path: 'cart', component: CartComponent },
])
],
shopping_cartCheckout
顯示購物車商品
本節(jié)將告訴你如何修改購物車組件以使用購物車服務來顯示購物車中的商品。
- 在 ?
cart.component.ts? 中,從 ?cart.service.ts? 文件中導入 ?CartService?。 - 注入 ?
CartService?,以便購物車組件可以使用它。 - 定義 ?
items?屬性,以便把商品存放在購物車中。 - 修改模板,加上標題,用帶有 ?
*ngFor? 的 ?? 來顯示每個購物車商品的名字和價格。生成的 ?
CartComponent?模板如下:Cart
{{ item.name }} {{ item.price | currency }}- 驗證你的購物車如預期般工作:
- 點擊 My Store
- 單擊商品名稱以顯示其詳細信息。
- 點擊Buy 將商品添加到購物車。
- 點擊Checkout查看購物車。
檢索運費價格
服務器通常采用流的形式返回數(shù)據(jù)。 流是很有用的,因為它們可以很容易地轉換返回的數(shù)據(jù),也可以修改你請求數(shù)據(jù)的方式。 Angular 的 HTTP 客戶端( ?
HttpClient?)是一種內置的方式,可以從外部 API 中獲取數(shù)據(jù),并以流的形式提供給你的應用。本節(jié)會為你展示如何使用 ?
HttpClient?從外部文件中檢索運費。在本指南的 StackBlitz 應用中,通過 ?
assets/shipping.json? 文件提供了一些預定義的配送數(shù)據(jù)。你可以利用這些數(shù)據(jù)為購物車中的商品添加運費。[ { "type": "Overnight", "price": 25.99 }, { "type": "2-Day", "price": 9.99 }, { "type": "Postal", "price": 2.99 } ]配置 AppModule 以使用 HttpClient
要使用 Angular 的 HTTP 客戶端之前,你必須先配置你的應用來使用 ?
HttpClientModule?。Angular 的 ?
HttpClientModule?中注冊了在整個應用中使用 ?HttpClient?服務的單個實例所需的服務提供者。- 在 ?
app.module.ts? 的頂部從 ?@angular/common/http? 包中導入 ?HttpClientModule?以及其它導入項。 由于有很多其它導入項,因此這里的代碼片段省略它們,以保持簡潔。請確?,F(xiàn)有的導入都還在原地。 - 把 ?
HttpClientModule?添加到 ?AppModule??@NgModule()? 的 ?imports?數(shù)組中,以便全局注冊 Angular 的 ?HttpClient?。
import { HttpClientModule } from '@angular/common/http';@NgModule({ imports: [ BrowserModule, HttpClientModule, ReactiveFormsModule, RouterModule.forRoot([ { path: '', component: ProductListComponent }, { path: 'products/:productId', component: ProductDetailsComponent }, { path: 'cart', component: CartComponent }, ]) ], declarations: [ AppComponent, TopBarComponent, ProductListComponent, ProductAlertsComponent, ProductDetailsComponent, CartComponent, ], bootstrap: [ AppComponent ] }) export class AppModule { }配置 CartService 以使用 HttpClient
下一步是注入 ?
HttpClient?服務到你的服務中, 這樣你的應用可以獲取數(shù)據(jù)并且與外部API和資源互動。- 從 ?
@angular/common/http? 包中導入 ?HttpClient?。 - 把 ?
HttpClient?注入到 ?CartService?的構造函數(shù)中:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Product } from './products';export class CartService { items: Product[] = []; constructor( private http: HttpClient ) {} /* . . . */ }配置 CartService 以得到商品價格
要從 ?
shapping.json? 中得到商品數(shù)據(jù), 你可以使用 ?HttpClient??get()? 方法。- 在 ?
cart.service.ts? 中 ?clearCart()? 方法下面,定義一個新的 ?getShippingPrices()? 方法,該方法會調用 ?HttpClient#get()?方法。
export class CartService { /* . . . */ getShippingPrices() { return this.http.get<{type: string, price: number}[]>('/assets/shipping.json'); } }創(chuàng)建配送組件
現(xiàn)在你的應用已經可以檢索配送數(shù)據(jù)了,你還要創(chuàng)建一個配送組件和相關的模板。
- 在終端窗口中運行如下命令,以生成名為 ?
shipping?的組件: - 在 ?
app.module.ts? 中,添加一個配送路由。其 ?path?為 ?shipping?,其 component 為 ?ShippingComponent?。
ng generate component shipping右鍵單擊 ?
app?文件夾,選擇 Angular Generator 和 Component 來生成一個名為 ?shipping?的新組件。import { Component } from '@angular/core'; @Component({ selector: 'app-shipping', templateUrl: './shipping.component.html', styleUrls: ['./shipping.component.css'] }) export class ShippingComponent { constructor() { } }@NgModule({ imports: [ BrowserModule, HttpClientModule, ReactiveFormsModule, RouterModule.forRoot([ { path: '', component: ProductListComponent }, { path: 'products/:productId', component: ProductDetailsComponent }, { path: 'cart', component: CartComponent }, { path: 'shipping', component: ShippingComponent }, ]) ], declarations: [ AppComponent, TopBarComponent, ProductListComponent, ProductAlertsComponent, ProductDetailsComponent, CartComponent, ShippingComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }新的配送組件尚未鏈接到任何其它組件,但你可以通過輸入其路由指定的 URL 在預覽窗格中看到它的模板。該 URL 具有以下模式:?
https://angular-ynqttp--4200.local.webcontainer.io/shipping? ,其中的 gets-started.stackblitz.io 部分可能與你的 StackBlitz 項目不同。配置 ShippingComponent 以使用 CartService
這個章節(jié)將指導你修改 ?
ShappingComponent?以通過HTTP從 ?shipping.json? 文件中提取商品數(shù)據(jù)。- 在 ?
shipping.component.ts? 中導入 ?CartService?。 - 把購物車服務注入到 ?
ShippingComponent?的 ?constructor()? 構造函數(shù)中: - 定義一個 ?
shippingCosts?屬性,并從 ?CartService?中利用購物車服務的 ?getShippingPrices()? 方法設置它。 - 利用 ?
async?管道修改配送組件的模板,以顯示配送類型和價格: - 在購物車視圖中添加一個到配送視圖的鏈接:
- 點擊 Checkout 按鈕,查看更新后的購物車。注意,修改本應用會導致預覽窗格刷新,這會清空購物車。
import { Component } from '@angular/core'; import { CartService } from '../cart.service';constructor(private cartService: CartService) { }export class ShippingComponent { shippingCosts = this.cartService.getShippingPrices(); }Shipping Prices
{{ shipping.type }} {{ shipping.price | currency }}?
async?管道從數(shù)據(jù)流中返回最新值,并在所屬組件的生命期內持續(xù)返回。當 Angular 銷毀該組件時,?async?管道會自動停止。Cart
{{ item.name }} {{ item.price | currency }}點擊此鏈接可以導航到運費頁。
分享名稱:創(chuàng)新互聯(lián)Angular教程:Angular管理數(shù)據(jù)
本文網址:http://m.5511xx.com/article/cdgiddh.html
import { Component } from '@angular/core';
import { CartService } from '../cart.service';export class CartComponent {
constructor(
private cartService: CartService
) { }
}
export class CartComponent {
items = this.cartService.getItems();
constructor(
private cartService: CartService
) { }
}這段代碼使用 ?CartService ?的 ?getItems()? 方法來設置條目。


咨詢
建站咨詢
