在 Nodejs 和 Angular10 中構建購物車
在本文中,我們將為我們的應用程序使用 Angular 10 構建購物車前端。
您可以查看我們已經發布的內置 Nodejs 的後端部分。
請注意,您需要在本地計算機上安裝 angular CLI。要升級到 Angular 10,您可以按照本教程進行操作。
要啟動,我們需要設置我們的應用程序目錄。創建一個angular-cart
桌面中的目錄並運行此命令來設置一個新的 Angular 項目:
cd desktop
mkdir angular-cart && cd angular-cart
ng new angular-cart
運行 ng new
命令將提示項目腳手架的一些問題。鍵入 y
將 Angular 路由添加到該項目並選擇 css
作為默認樣式表。
選擇這兩件事將創建一個新的 Angular 10 項目。您可以進入項目目錄,然後使用 code .
命令在 VS Code 中打開我們的項目。
為了服務我們的應用程序,我們可以運行 ng serve
這將在端口 4200 上打開我們的應用程序。
我們將繼續為應用程序設置用戶界面。您可以從 WrapPixel 的 UI Kit 中獲取我們所有的 UI 組件。
WrapPixel 是一個在線模板商店,您可以在其中獲得出色的 Angular Dashboard Template 和 Angular Material Themes。
我們將創建用於列出產品和購物車詳細信息的組件。我們還將為頁面導航定義一個導航欄組件。
要創建一個組件,請在您的終端上運行:
ng g c components/cart
ng g c components/navbar
ng g c components/products
這將創建一個組件目錄並創建一個購物車模塊,我們將在其中定義我們的標記和样式。
我們需要通過將 CDN 添加到 src/dex.html
來將 Bootstrap 配置到我們的應用程序中 文件。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AngularCart</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
讓我們通過編輯 components/navbar/navbar.components.html
中的代碼來定義我們的導航欄 對此:
<nav class="navbar navbar-expand-lg navbar-light bg-info">
<div class="container">
<a routerLink="/" class="navbar-brand">Angular Cart</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse justify-content-end" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a routerLink="/" class="nav-link">Home </a>
</li>
<li class="nav-item">
<a routerLink="/cart" class="nav-link">Cart </a>
</li>
</ul>
</div>
</div>
</nav>
然後修改app/app.components.html
中的代碼 對此:
<app-navbar></app-navbar>
<section>
<div class="banner-innerpage" style="
background-image: url(https://images.pexels.com/photos/1005638/pexels-photo-1005638.jpeg?cs=srgb&dl=pexels-oleg-magni-1005638.jpg&fm=jpg);
">
<div class="container">
<!-- Row -->
<div class="row justify-content-center">
<!-- Column -->
<div class="col-md-6 align-self-center text-center" data-aos="fade-down" data-aos-duration="1200">
<h1 class="title">Shop listing</h1>
<h6 class="subtitle op-8">
We are small team of creative people working together.
</h6>
</div>
<!-- Column -->
</div>
</div>
</div>
</section>
<router-outlet></router-outlet>
我們將在app.component.css
中添加一些樣式 :
.banner-innerpage {
padding: 150px 0 100px;
background-size: cover;
background-position: center center;
}
.banner-innerpage .title {
color: #ffffff;
text-transform: uppercase;
font-weight: 700;
font-size: 40px;
line-height: 40px;
}
.banner-innerpage .subtitle {
color: #ffffff;
}
.shop-listing .shop-hover {
position: relative;
}
.shop-listing .shop-hover .card-img-overlay {
display: none;
background: rgba(255, 255, 255, 0.5);
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
}
.shop-listing .shop-hover:hover .card-img-overlay {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
.shop-listing .shop-hover .label {
padding: 5px 10px;
position: absolute;
top: 10px;
right: 10px;
}
/*******************
shop table
*******************/
.shop-table td {
padding: 30px 0;
}
讓我們在 app/app-routing.module.ts
中註冊我們的路線 文件:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CartComponent } from './components/cart/cart.component';
import { ProductsComponent } from './components/products/products.component';
const routes: Routes = [
{ path: '', component: ProductsComponent },
{ path: 'cart', component: CartComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
完成後,我們現在可以通過定義路由鏈接來處理導航欄組件中的路由:
<nav class="navbar navbar-expand-lg navbar-light bg-info">
<div class="container">
<a routerLink="/" class="navbar-brand">Angular Cart</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse justify-content-end" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a routerLink="/" class="nav-link">Home </a>
</li>
<li class="nav-item">
<a routerLink="/cart" class="nav-link">Cart </a>
</li>
</ul>
</div>
</div>
</nav>
我們現在可以創建一些服務來處理我們的 HTTP 請求。要在 Angular 中創建服務,請打開終端並輸入以下內容:
ng g s http
這將創建一個 http.service.ts
文件。我們將引入 Angular HttpClient
用於發出 http 請求,然後定義我們的 http 服務:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../environments/environment';
@Injectable({
providedIn: 'root',
})
export class HttpService {
constructor(private http: HttpClient) {}
getAllProducts() {
return this.http.get(`${environment.baseURL}/product`);
}
addToCart(payload) {
return this.http.post(`${environment.baseURL}/cart`, payload);
}
getCartItems() {
return this.http.get(`${environment.baseURL}/cart`);
}
increaseQty(payload) {
return this.http.post(`${environment.baseURL}/cart`, payload);
}
emptyCart() {
return this.http.delete(`${environment.baseURL}/cart/empty-cart`);
}
}
我們將服務器的 baseURL 存儲在 environment.ts
文件:
baseURL: 'http://localhost:4000'
我們現在可以在我們的組件中使用此服務。我們將從產品組件開始,我們將在其中實現產品列表並將產品項目添加到購物車。
為了能夠使用 Angular httpClient
模塊我們必須通過將它導入到我們的 app/app.module.ts
中來在我們的應用程序中全局註冊它 文件:
import { HttpClientModule } from '@angular/common/http';
imports: [... other modules,HttpClientModule]
讓我們在 app/components/products.component.ts
中修改我們的代碼 文件到這個:
import { Component, OnInit } from '@angular/core';
import { HttpService } from '../../http.service';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css'],
})
export class ProductsComponent implements OnInit {
products: Array<object> = [];
constructor(private http: HttpService) {}
_getProducts(): void {
this.http.getAllProducts().subscribe((data: any) => {
this.products = data.data;
console.log(this.products);
});
}
_addItemToCart( id, quantity): void {
let payload = {
productId: id,
quantity,
};
this.http.addToCart(payload).subscribe(() => {
this._getProducts();
alert('Product Added');
});
}
ngOnInit(): void {
this._getProducts();
}
}
然後通過編輯 products.component.ts
為應用程序設置我們的模板 文件到這個:
<section>
<div class="spacer">
<div class="container">
<div class="row mt-5">
<div class="col-lg-9">
<div class="row shop-listing">
<div class="col-lg-4" *ngFor="let product of products">
<div class="card shop-hover border-0">
<img [src]="'http://localhost:5000/' + product.image" alt="wrapkit" class="img-fluid" />
<div class="card-img-overlay align-items-center">
<button class="btn btn-md btn-info" (click)="_addItemToCart(product._id, 1)">Add to Cart</button>
</div>
</div>
<div class="card border-0">
<h6>
<a href="#" class="link">{{ product.name }}</a>
</h6>
<h6 class="subtitle">by Wisdom</h6>
<h5 class="font-medium m-b-30">
${{product.price}}
</h5>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
有了這個,我們現在可以列出我們所有的產品並將產品添加到購物車。
我們將繼續實施購物車部分。讓我們在 app/components/cart.component.ts
中定義我們所有的購物車方法 文件:
import { Component, OnInit } from '@angular/core';
import { HttpService } from '../../http.service';
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['./cart.component.css'],
})
export class CartComponent implements OnInit {
carts;
cartDetails;
constructor(private http: HttpService) {}
_getCart(): void {
this.http.getCartItems().subscribe((data: any) => {
this.carts = data.data;
// this.cartDetails = data.data;
console.log(this.carts);
});
}
_increamentQTY(id, quantity): void {
const payload = {
productId: id,
quantity,
};
this.http.increaseQty(payload).subscribe(() => {
this._getCart();
alert('Product Added');
});
}
_emptyCart(): void {
this.http.emptyCart().subscribe(() => {
this._getCart();
alert('Cart Emptied');
});
}
ngOnInit(): void {
this._getCart();
}
}
並且還設置了一個用於在 html 文件中列出購物車項目的模板:
<section>
<div class="spacer">
<div class="container">
<div class="row mt-5">
<div class="col-lg-9">
<div class="row shop-listing">
<table class="table shop-table" *ngIf="carts">
<tr>
<th class="b-0">Name</th>
<th class="b-0">Price</th>
<th class="b-0">Quantity</th>
<th class="b-0 text-right">Total Price</th>
</tr>
<tr *ngFor="let item of carts.items">
<td>{{ item.productId.name }}</td>
<td>{{ item.productId.price }}</td>
<td>
<button class="btn btn-primary btn-sm" (click)="_increamentQTY(item.productId._id,1)">+</button>
{{ item.quantity }}
<button class="btn btn-primary btn-sm">-</button>
</td>
<td class="text-right">
<h5 class="font-medium m-b-30">{{ item.total }}</h5>
</td>
</tr>
<tr>
<td colspan="3" align="right">Subtotal :{{ carts.subTotal }}</td>
<td colspan="4" align="right">
<button class="btn btn-danger" (click)="_emptyCart()">Empty Cart</button>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
練習
- 實現遞減功能
- 實施從購物車中刪除產品
實施此操作後,將您的工作推送到 git 並在評論部分添加鏈接。讓我們玩得開心😁