来自官网学习个人总结
🛒 购物车案例
需求
- 商品详情界面添加一个 Buy button,将当前商品信息添加到购物车列表
- 添加购物车组件。展示这个列表
- 添加购买组件,通过使用 Angular's HttpClient 得到的 json 数据展示商品的价格信息
💻getting start
- 生成一个购物车 service:
ng generate service cart
在 angular 中,service 被认为是可以在全局都使用的 class 的实例
// cart.service.ts
import { Product } from "./products";
export class CartService {
items: Product[] = [];
addToCart(product: Product) {
this.items.push(product);
}
getItems() {
return this.items;
}
clearCart() {
this.items = [];
return this.items;
}
/* . . . */
}
- 购物车 service 的使用:
导入 service,并将其注入到constructor()
定义加入购物车函数,可在对应的 html 中直接调用
import { CartService } from '../cart.service';
export class ProductDetailsComponent implements OnInit {
constructor(
private cartService: CartService
) { }
addToCart(product: Product) {
this.cartService.addToCart(product);
window.alert('Your product has been added to the cart!');
}
}
- 生成一个购物车组件:
ng generate component cart
这个时候我们的app.module.ts中已经将其添加到declarations中了,但是我们仍需在这个文件中加入它的路由,让我们的 Buy button 点击后顺利进入
在购物车组件中展示商品列表信息
/* . 略. . */
- 通过
HttpClient调用 API 实现购买。
- 在 app.module.ts 的顶部引入
HttpClientModule
//app.module.ts 的顶部引入,要在其他import上面
import { HttpClientModule } from "@angular/common/http";
@NgModule({
imports: [
HttpClientModule,
//...
]
})
- 在 cart service 中,把
HttpClient注入到constructor
import { HttpClient } from "@angular/common/http";
export class CartService {
items: Product[] = [];
constructor(private http: HttpClient) {}
getShippingPrices() {
return this.http.get<{ type: string; price: number }[]>(
"/assets/shipping.json"
);
}
/* . . . */
}