# 0531 前端 # addproduct html ``` <h1>新增商品</h1> <form #tForm="ngForm" (ngSubmit)="doSubmit(tForm)"> <div class="form-group"> <div class="form-field"> <label for="productName" style="font-size: 23px;margin-top: 15px;">商品名稱</label><br /> <input type="text" #tName="ngModel" name="name" class="form-control" id="productName" aria-describedby="emailHelp" placeholder="請輸入商品名稱..." [(ngModel)]="name" required="required"> <ng-container *ngIf="tName.invalid && tForm.submitted"> <p class="error-message" *ngIf="tName.errors?.required">此欄位為必填</p> </ng-container> </div> </div> <div class="form-group"> <div class="form-field"> <label for="productPrice" style="font-size: 23px;margin-top: 15px;">商品價錢</label><br /> <input type="number" #tprice="ngModel" name="price" class="form-control" id="productPrice" placeholder="請輸入商品價錢..." [(ngModel)]="price" required="required"> <ng-container *ngIf="tprice.invalid && tForm.submitted"> <p class="error-message" *ngIf="tprice.errors?.required">此欄位為必填</p> </ng-container> </div> </div> <div class="form-group"> <div class="form-field"> <label for="productDetail" style="font-size: 23px;margin-top: 15px;">商品詳細說明</label><br /> <input type="text" #tdetail="ngModel" name="detail" class="form-control" id="productDetail" placeholder="請輸入商品詳細說明..." [(ngModel)]="detail" required="required"> <ng-container *ngIf="tdetail.invalid && tForm.submitted"> <p class="error-message" *ngIf="tdetail.errors?.required">此欄位為必填</p> </ng-container> </div> </div> <div class="form-group"> <div class="form-field"> <label for="productCategory" style="font-size: 23px;margin-top: 15px;">商品分類</label><br /> <select type="select" #tcategory="ngModel" name="category" class="form-control" id="productCategory" placeholder="請輸入商品分類..." [(ngModel)]="category" required="required"> <option *ngFor="let cate of allCategory" value="{{cate.id}}">{{cate.name}}</option> <!-- <option>iPad</option> --> </select> <ng-container *ngIf="tcategory.invalid && tForm.submitted"> <p class="error-message" *ngIf="tcategory.errors?.required">此欄位為必填</p> </ng-container> </div> </div> <button type="submit" class="btn btn-primary" [disabled]="tForm.invalid" (click)="AddProduct()">送出</button> <button type="submit" class="btn btn-secondary" (click)="tForm.reset()">清除</button> </form> <br/><br/><br/><br/><br/> ``` # ts ``` import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; const product_url="http://localhost:8080/api/product/"; const productCategory_url ="http://localhost:8080/api/productCategory/" @Component({ selector: 'app-addproduct', templateUrl: './addproduct.component.html', styleUrls: ['./addproduct.component.css'] }) export class AddProductComponent implements OnInit { // id:number; name:string; price: number; filepath: string; // quant:number; detail:string; // upDate:Date; // product:Object; products: Object; category:object; allCategory:any=[]; constructor(private http: HttpClient) { } ngOnInit(): void { this.getCategory(); } AddProduct(){ const c = { name: this.name, price: this.price,detail:this.detail ,filepath:this.filepath} this.http.post(product_url+'all/'+this.category, c).subscribe(d=>{ console.log("新增:",d) }) window.alert("成功新增商品!"); window.location.reload() } getCategory(){ this.http.get(productCategory_url+'all').subscribe(d=>{ this.allCategory=d; console.log(this.allCategory) }) } doSubmit(addproduct: AddProductComponent): void { console.log('submit new data', addproduct); } } ``` # cart html ``` <br/><br/> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"> <div class="container padding-bottom-3x mb-1"> <!-- Shopping Cart--> <div class="table-responsive shopping-cart"> <table class="table" style="background-color:#e0e0e0; border-color: white;"> <thead> <tr> <th class="text-center">商品名稱</th> <th class="text-center">說明</th> <!--<th class="text-center"> 數量 </th>--> <th class="text-center">價錢</th> <th class="text-center"><a class="btn btn-sm btn-outline-danger" (click)="deleteAllCart()">Clear Cart</a></th> </tr> </thead> <tbody> <tr *ngFor="let cart of carts"> <td> <div class="product-item"> <!--<a class="product-thumb" href="#"><img src="https://www.bootdey.com/image/220x180/FF0000/000000" alt="Product"></a>--> <div class="product-info"> <h4 class="product-title class text-center"><a href="#">{{cart.name}}</a></h4><!--<span><em>Size:</em> 10.5</span><span><em>Color:</em> Dark Blue</span>--> </div> </div> </td> <td class="text-center text-lg text-medium">{{cart.detail}}</td> <td class="text-center text-lg text-medium">$ {{cart.price}}</td> <td class="text-center"><a class="remove-from-cart" data-toggle="tooltip" title="" data-original-title="Remove item" (click)="deletecart(cart.id)"><i class="fa fa-trash"></i></a></td> </tr> </tbody> </table> </div> <div class="shopping-cart-footer"> <div class="column text-lg" style="font-size:20px;">總價: <span class="text-medium">$ {{totalPrice}}</span></div> </div> <div class="shopping-cart-footer"> <div class="column"><a class="btn btn-outline-secondary" routerLink="/"><i class="icon-arrow-left"></i>&nbsp;Back to Shopping</a></div> <div class="column"><a class="btn btn-success" href="#">Checkout</a></div> </div> </div> <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> ``` # ts ``` import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; const customer_url = "http://localhost:8080/api/customer/" const product_url = "http://localhost:8080/api/product/"; @Component({ selector: 'app-cart', templateUrl: './cart.component.html', styleUrls: ['./cart.component.css'], styles: [ ` .dark-modal .modal-content { background-color: #292b2c; color: white; } .dark-modal .close { color: white; } .light-blue-backdrop { background-color: #5cb3fd; } `, ], }) export class CartComponent implements OnInit { // id: number; name: string; price: number; // amount: number; carts: any = []; // cart: object; customers: any = []; totalPrice: number = 0; allCarts: any[]; constructor(private http: HttpClient) { this.name = sessionStorage.getItem('user') } ngOnInit(): void { this.getAllCart(); } getAllCart() { this.http.get(customer_url + 'all').subscribe(d => { this.customers = d this.customers.forEach(element => { if (element.name == this.name) { this.carts = element.products this.carts.forEach((element: any = []) => { this.totalPrice = this.totalPrice + element.price console.log("價錢", element.price) }); } }); console.log(this.customers) }) } deletecart(id: number) { this.http.get(customer_url + 'all').subscribe(d => { this.customers = d this.customers.forEach(element => { if (element.name == this.name) { console.log(id) this.http.delete(product_url + element.id + '/' + id).subscribe(res => console.log("Result", res)); window.location.reload() } }); }) } deleteAllCart() { this.http.get(customer_url + 'all').subscribe(d => { this.customers = d this.customers.forEach(element => { if (element.name == this.name) { this.http.delete(product_url + element.id + '/all').subscribe(res => console.log("Result", res)); window.location.reload() } }); }) } } ``` # categoryipad html ``` <!-- Header--> <header class="py-5" style="background-color:#5E5A54;"> <div class="container px-4 px-lg-5 my-5"> <div class="text-center text-white"> <h1 class="display-4 fw-bolder">iPad</h1> <p class="lead fw-normal text-white-50 mb-0"></p> </div> </div> </header> <section class="py-5" style="background-color:#FFF8EC;"> <div class="container px-4 px-lg-5 mt-5"> <div class="row gx-4 gx-lg-5 row-cols-2 row-cols-md-3 row-cols-xl-4 justify-content-center"> <div class="col mb-5" *ngFor="let category of category"> <div class="card h-100"> <!-- Sale badge--> <!--<div class="badge bg-dark text-white position-absolute" style="top: 0.5rem; right: 0.5rem">Sale</div>--> <!-- Product image--> <img class="card-img-top" src="{{category.filePath}}" style="height:250px ;width:268px;" alt="{{category.name}}" /> <!--<img class="card-img-top" src="https://dummyimage.com/450x300/dee2e6/6c757d.jpg" alt="..." />--> <!-- Product details--> <div class="card-body p-4"> <div class="text-center"> <!-- Product name--> <h5 class="fw-bolder">{{category.name}}</h5> <p>{{category.detail}}</p> <!-- Product reviews <div class="d-flex justify-content-center small text-warning mb-2"> <div class="bi-star-fill"></div> <div class="bi-star-fill"></div> <div class="bi-star-fill"></div> <div class="bi-star-fill"></div> <div class="bi-star-fill"></div> </div>--> <!-- Product price--> <!--<span class="text-muted text-decoration-line-through">$20.00</span>--> ${{category.price}} </div> </div> <!-- Product actions--> <div class="card-footer p-4 pt-0 border-top-0 bg-transparent"> <div class="text-center"> <a class="btn btn-outline-dark mt-auto" (click)="addToCart(category.id,category.name,category.price,category.detail)">Add to cart</a> </div> <br /> </div> </div> </div> </div> </div> </section> ``` # ts ``` import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; const productCategory_url ="http://localhost:8080/api/productCategory/" const product_url = "http://localhost:8080/api/product/"; const customer_url = "http://localhost:8080/api/customer/"; @Component({ selector: 'app-category-ipad', templateUrl: './category-ipad.component.html', styleUrls: ['./category-ipad.component.css'] }) export class CategoryIpadComponent implements OnInit { // id:number; // name: string; // price: number; // detail: string; // filePath:string; // allproducts:object; category:object; compareRes: Object; allcustomers:any=[]; userSession = sessionStorage.getItem('user'); customer_id: object; ngOnInit(): void { this.getCategoryList(); } constructor(private http: HttpClient, private route: ActivatedRoute){} getCategoryList(){ this.http.get(productCategory_url+'all').subscribe(d=>{ this.category=d[0].products; console.log(this.category) }) } deleteproduct(id: number) { this.http.delete(product_url + id).subscribe(res => console.log("Result", res)); window.location.reload() } // addToCart(name: string, price: number,detail:string) { // const c = { name, price,detail } // // 將name帶到後端檢查是否存在 // this.http.post(cart_url + name, name).subscribe(d => { // // console.log("是否存在=>", d) // this.compareRes = d; // // 如果回傳回來為true那就無法新增並提示訊息 // if (this.compareRes == true) { // window.alert(name + " 購物車已經存在"); // console.log("已經存在") // // window.location.reload() // } else if (this.compareRes == false) { // this.http.post(cart_url + 'all', c).subscribe(d => { console.log("新增:", d) }) // window.location.reload() // } // }) // } addToCart(product_id: number, name: string, price: number, detail: string) { // 取得所有用戶資訊 this.http.get(customer_url + 'all').subscribe(c => { this.allcustomers = c; this.allcustomers.forEach(element => { // 如果比對到相同的名稱,取出customer的id if (this.userSession === element.name) { this.customer_id = element.id; const c = { product_id, name, price, detail }; this.http.post(customer_url + element.id + '/' + product_id, c).subscribe(d => { console.log(customer_url + element.id + '/' + product_id) }) } }) }); } } ``` # categoryiphone html ``` <!-- Header--> <header class="py-5" style="background-color:#5E5A54;"> <div class="container px-4 px-lg-5 my-5"> <div class="text-center text-white"> <h1 class="display-4 fw-bolder">Iphone</h1> <p class="lead fw-normal text-white-50 mb-0"></p> </div> </div> </header> <section class="py-5" style="background-color:#FFF8EC;"> <div class="container px-4 px-lg-5 mt-5"> <div class="row gx-4 gx-lg-5 row-cols-2 row-cols-md-3 row-cols-xl-4 justify-content-center"> <div class="col mb-5" *ngFor="let category of category"> <div class="card h-100"> <!-- Sale badge--> <!--<div class="badge bg-dark text-white position-absolute" style="top: 0.5rem; right: 0.5rem">Sale</div>--> <!-- Product image--> <img class="card-img-top" src="{{category.filePath}}" style="height:250px ;;width:268px;" alt="{{category.name}}" /> <!--<img class="card-img-top" src="https://dummyimage.com/450x300/dee2e6/6c757d.jpg" alt="..." />--> <!-- Product details--> <div class="card-body p-4"> <div class="text-center"> <!-- Product name--> <h5 class="fw-bolder">{{category.name}}</h5> <p>{{category.detail}}</p> <!-- Product reviews <div class="d-flex justify-content-center small text-warning mb-2"> <div class="bi-star-fill"></div> <div class="bi-star-fill"></div> <div class="bi-star-fill"></div> <div class="bi-star-fill"></div> <div class="bi-star-fill"></div> </div>--> <!-- Product price--> <!--<span class="text-muted text-decoration-line-through">$20.00</span>--> ${{category.price}} </div> </div> <!-- Product actions--> <div class="card-footer p-4 pt-0 border-top-0 bg-transparent"> <div class="text-center"> <a class="btn btn-outline-dark mt-auto" (click)="addToCart(category.id,category.name,category.price,category.detail)">Add to cart</a> </div> </div> </div> </div> </div> </div> </section> ``` # ts ``` import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; const productCategory_url ="http://localhost:8080/api/productCategory/" const product_url = "http://localhost:8080/api/product/"; const customer_url = "http://localhost:8080/api/customer/"; @Component({ selector: 'app-category-iphone', templateUrl: './category-iphone.component.html', styleUrls: ['./category-iphone.component.css'] }) export class CategoryIphoneComponent implements OnInit { // id:number; // name: string; // price: number; // detail: string; // filePath:string; // allproducts:object; category:object; compareRes: Object; allcustomers:any=[]; userSession = sessionStorage.getItem('user'); customer_id: object; ngOnInit(): void { this.getCategoryList(); } constructor(private http: HttpClient){} getCategoryList(){ this.http.get(productCategory_url+'all').subscribe(d=>{ this.category=d[1].products; console.log(this.category) }) } deleteproduct(id: number) { this.http.delete(product_url + id).subscribe(res => console.log("Result", res)); window.location.reload() } // addToCart(name: string, price: number,detail:string) { // const c = { name, price,detail} // // 將name帶到後端檢查是否存在 // this.http.post(cart_url + name, name).subscribe(d => { // // console.log("是否存在=>", d) // this.compareRes = d; // // 如果回傳回來為true那就無法新增並提示訊息 // if (this.compareRes == true) { // window.alert(name + " 購物車已經存在"); // console.log("已經存在") // // window.location.reload() // } else if (this.compareRes == false) { // this.http.post(cart_url + 'all', c).subscribe(d => { console.log("新增:", d) }) // window.location.reload() // } // }) // } addToCart(product_id: number, name: string, price: number, detail: string) { // 取得所有用戶資訊 this.http.get(customer_url + 'all').subscribe(c => { this.allcustomers = c; this.allcustomers.forEach(element => { // 如果比對到相同的名稱,取出customer的id if (this.userSession === element.name) { this.customer_id = element.id; const c = { product_id, name, price, detail }; this.http.post(customer_url + element.id + '/' + product_id, c).subscribe(d => { console.log(customer_url + element.id + '/' + product_id) }) } }) }); } } ``` # login html ``` <!-- <div *ngIf="!isLogin()"> <div style="color: red;" *ngIf="isFail">{{warnMessage}}</div> <div> <label>帳號<input type="text" name="username" [(ngModel)]="username"></label> <label>信箱<input type="text" name="email" [(ngModel)]="email"></label><br /> <button (click)="login()">Login</button> </div> </div> <hr> <div *ngIf="isLogin()"> <h1>Hello {{username}}</h1> <button (click)="logout()">logout</button> </div> --> <html> <body> <div class="system_name"> <h2>登入</h2> </div> <div class="login_page"> <div id="container1"> <div class="login" *ngIf="!isLogin()"> <h3>Login</h3> <div> <input type="text" id="username" name="username" placeholder="帳號" [(ngModel)]="username" required> <div class="tab"></div> <input type="text" id="password" name="password" placeholder="密碼" [(ngModel)]="password" required> <div class="tab"></div> <div style="color: red; margin-left: 40px;" *ngIf="isFail">{{warnMessage}}</div> <button type="button" class="btn btn-warning" (click)="login()">登入</button> </div> <!-- <h5 onclick="show_hide()">註冊帳號</h5> --> <button type="button" class="btn btn-warning" routerLink='/register'>註冊帳號</button> <!-- <button type="button" class="btn btn-warning" routerLink='/register'>修改密碼</button> --> </div> <!-- login end--> <div *ngIf="isLogin()"> <br/><br/><br/> <h1 style="size: 16px;margin-left: 32%;">登入成功</h1> <br/><br/><br/> <button type="button" class="btn btn-warning" routerLink="/">前往首頁</button> <button type="button" class="btn btn-warning" (click)="logout()" routerLink="/">登出</button> </div> </div><!-- container1 end--> </div><!-- login_page end--> </body> </html> <br><br><br><br><br><br> ``` # ts ``` import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; const customer_url="http://localhost:8080/api/customer/"; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { username :string; password :string; isFail: boolean =false; warnMessage:String='帳號或密碼錯誤'; // customer:Object; // customers:Object; allcustomers: any=[]; ngOnInit(): void { this.getAllCustomerList(); } constructor(private http: HttpClient){} getAllCustomerList(){ this.http.get(customer_url+'all').subscribe(c => { this.allcustomers.push(c) }) } login(){ sessionStorage.removeItem('user'); console.log(this.allcustomers[0]) this.allcustomers[0].forEach(element => { if(this.username===element.name && this.password===element.password){ sessionStorage.setItem('user',this.username); this.isFail=false; window.location.reload() }else{ this.isFail=true; } }); } isLogin(){ return sessionStorage.getItem('user')!=null; } logout(){ sessionStorage.removeItem('user'); } } ``` # modify product html ``` <h1>修改商品</h1> <form #tForm="ngForm" (ngSubmit)="doSubmit(tForm)"> <div class="form-group"> <div class="form-field"> <label for="productName" style="font-size: 23px;margin-top: 15px;">商品名稱</label><br /> <input type="text" #tName="ngModel" name="name" class="form-control" id="productName" aria-describedby="emailHelp" placeholder="請輸入商品名稱..." [(ngModel)]="name" required="required"> <ng-container *ngIf="tName.invalid && tForm.submitted"> <p class="error-message" *ngIf="tName.errors?.required">此欄位為必填</p> </ng-container> </div> </div> <div class="form-group"> <div class="form-field"> <label for="productPrice" style="font-size: 23px;margin-top: 15px;">商品價錢</label><br /> <input type="number" #tprice="ngModel" name="price" class="form-control" id="productPrice" placeholder="請輸入商品價錢..." [(ngModel)]="price" required="required"> <ng-container *ngIf="tprice.invalid && tForm.submitted"> <p class="error-message" *ngIf="tprice.errors?.required">此欄位為必填</p> </ng-container> </div> </div> <div class="form-group"> <div class="form-field"> <label for="productDetail" style="font-size: 23px;margin-top: 15px;">商品詳細說明</label><br /> <input type="text" #tdetail="ngModel" name="detail" class="form-control" id="productDetail" placeholder="請輸入商品詳細說明..." [(ngModel)]="detail" required="required"> <ng-container *ngIf="tdetail.invalid && tForm.submitted"> <p class="error-message" *ngIf="tdetail.errors?.required">此欄位為必填</p> </ng-container> </div> </div> <div class="form-group"> <div class="form-field"> <label for="productCategory" style="font-size: 23px;margin-top: 15px;">商品分類</label><br /> <select type="select" #tcategory="ngModel" name="category" class="form-control" id="productCategory" placeholder="請輸入商品分類..." [(ngModel)]="category" required="required"> <option *ngFor="let cate of allCategory" value="{{cate.id}}">{{cate.name}}</option> </select> <ng-container *ngIf="tcategory.invalid && tForm.submitted"> <p class="error-message" *ngIf="tcategory.errors?.required">此欄位為必填</p> </ng-container> </div> </div> <button type="submit" class="btn btn-primary" [disabled]="tForm.invalid" (click)="ModifyProduct()" routerLink="/">送出</button> <button type="submit" class="btn btn-secondary" (click)="tForm.reset()">清除</button> </form> <br/><br/><br/><br/><br/> ``` # ts ``` import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { AddProductComponent } from '../addproduct/addproduct.component'; const Modifyproduct_url="http://localhost:8080/api/product/"; const productCategory_url ="http://localhost:8080/api/productCategory/" @Component({ selector: 'app-modify-product', templateUrl: './modify-product.component.html', styleUrls: ['./modify-product.component.css'] }) export class ModifyProductComponent implements OnInit { // id:number; name:string; price: number; detail:string; // allproducts: Object; // filePath:string; p: { id: number,name:string,price:number,detail:string} location: any; category:string; // cate:object; allCategory:any=[]; constructor(private http: HttpClient, private route: ActivatedRoute) { } ngOnInit(): void { this.p = { id: this.route.snapshot.params['id'], name:this.route.snapshot.params['name'], price:this.route.snapshot.params['price'], detail:this.route.snapshot.params['detail'] }; this.route.params.subscribe((params: Params) => { this.p.id = params['id']; this.p.name = params['name']; this.p.price = params['price']; this.p.detail = params['detail']; }); this.name=this.p.name; this.price=this.p.price; this.detail=this.p.detail; this.getCategory(); } ModifyProduct() { const c = { name: this.name, price: this.price, detail: this.detail} this.http.put(Modifyproduct_url + this.p.id+'/'+this.category,c).subscribe(d => { console.log("修改:", d) }) console.log(this.category) window.alert("修改成功!"); } goBack(): void { this.location.back(); } getCategory(){ this.http.get(productCategory_url+'all').subscribe(d=>{ this.allCategory=d; // console.log(this.allCategory) }) } doSubmit(addproduct: AddProductComponent): void { // console.log('submit new data', addproduct); } } ``` # product html ``` <!-- Header--> <header class="py-5" style="background-color:#5E5A54;"> <div class="container px-4 px-lg-5 my-5"> <div class="text-center text-white"> <h1 class="display-4 fw-bolder">ALL</h1> <p class="lead fw-normal text-white-50 mb-0"></p> </div> </div> </header> <section class="py-5" style="background-color:#FFF8EC;"> <div class="container px-4 px-lg-5 mt-5"> <div class="row gx-4 gx-lg-5 row-cols-2 row-cols-md-3 row-cols-xl-4 justify-content-center"> <div class="col mb-5" *ngFor="let product of products"> <div class="card h-100"> <!-- Sale badge--> <!--<div class="badge bg-dark text-white position-absolute" style="top: 0.5rem; right: 0.5rem">Sale</div>--> <!-- Product image--> <img class="card-img-top" src="{{product.filePath}}" style="height:250px ;width:268px;" alt="{{product.name}}" /> <!--<img class="card-img-top" src="https://dummyimage.com/450x300/dee2e6/6c757d.jpg" alt="..." />--> <!-- Product details--> <div class="card-body p-4"> <div class="text-center"> <!-- Product name--> <h5 class="fw-bolder">{{product.name}}</h5> <p>{{product.detail}} </p> <!-- Product reviews <div class="d-flex justify-content-center small text-warning mb-2"> <div class="bi-star-fill"></div> <div class="bi-star-fill"></div> <div class="bi-star-fill"></div> <div class="bi-star-fill"></div> <div class="bi-star-fill"></div> </div>--> <!-- Product price--> <!--<span class="text-muted text-decoration-line-through">$20.00</span>--> ${{product.price}} </div> </div> <!-- Product actions--> <div class="card-footer p-4 pt-0 border-top-0 bg-transparent"> <div class="login" *ngIf="isLogin()"> <div class="text-center"> <a class="btn btn-outline-dark mt-auto" (click)="addToCart(product.id,product.name,product.price,product.detail)">Add to cart</a> </div> </div> <br /> <div class="text-center"> <a class="btn btn-outline-dark mt-auto" routerLink="/product/{{product.id}}/{{product.name}}/{{product.price}}/{{product.detail}}" routerLinkActive="active">Modify Product</a> </div> <br /> <div class="text-center"> <a class="btn btn-outline-dark mt-auto" (click)="deleteproduct(product.id)">Delete Product</a> </div> </div> </div> </div> </div> </div> </section> ``` # ts ``` import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; const product_url = "http://localhost:8080/api/product/"; const customer_url = "http://localhost:8080/api/customer/"; @Component({ selector: 'app-product', templateUrl: './product.component.html', styleUrls: ['./product.component.css'] }) export class ProductComponent implements OnInit { // id: number; // name: string; // price: number; // filePath: string; // amount: number; // detail: string; // upDate: Date; // category: string; // product: Object; products: Object; compareRes: Object; userSession = sessionStorage.getItem('user'); customer_id: object; allcustomers: any = []; constructor(private http: HttpClient) { } ngOnInit() { // this.getAllCart(); this.getproductList(); } getproductList() { this.http.get(product_url + 'all').subscribe(d => { this.products = d console.log(this.products) }) } deleteproduct(id: number) { let text; if (confirm("Press a button!") == true) { this.http.delete(product_url + id).subscribe(res => console.log("Result", res)); console.log(product_url + id) window.location.reload() } else { text = "You canceled!"; } document.getElementById("demo").innerHTML = text; } // addToCart(product_id: number,name: string, price: number,detail:string) { // const c = { name, price,detail} // // 將name帶到後端檢查是否存在 // this.http.post(product_url + name, name).subscribe(d => { // this.compareRes = d; // // 如果回傳回來為true那就無法新增並提示訊息 // if (this.compareRes == true) { // window.alert(name + " 購物車已經存在"); // console.log("已經存在") // // window.location.reload() // } else if (this.compareRes == false) { // this.http.get(product_url + 'all').subscribe(c => { // this.allcustomers = c; // this.allcustomers.forEach(element => { // // 如果比對到相同的名稱,取出customer的id // if (this.userSession === element.name) { // this.customer_id=element.id; // const c={product_id,name,price,detail}; // this.http.post(customer_url + element.id+'/' + product_id,c).subscribe(d => { // console.log(customer_url + element.id+'/' + product_id) // }) // } // }) // }); // window.location.reload() // } // }) // } addToCart(product_id: number, name: string, price: number, detail: string) { // 取得所有用戶資訊 this.http.get(customer_url + 'all').subscribe(c => { this.allcustomers = c; this.allcustomers.forEach(element => { // 如果比對到相同的名稱,取出customer的id if (this.userSession === element.name) { this.customer_id = element.id; const c = { product_id, name, price, detail }; this.http.post(customer_url + element.id + '/' + product_id, c).subscribe(d => { console.log(customer_url + element.id + '/' + product_id) }) } }) }); } isLogin() { return sessionStorage.getItem('user') != null; } } ``` # register html ``` <html> <body> <div class="system_name"> <h2>註冊</h2> </div> <div class="login_page"> <div id="container1"> <div class="register"> <h3>Register</h3> <div> <input type="text" id="username" name="username" placeholder="帳號" [(ngModel)]="username" required="required"> <div class="tab"></div> <input type="text" id="password" name="password" placeholder="密碼" [(ngModel)]="password" required="required"> <div class="tab"></div> <div style="color: red; margin-left: 40px;" *ngIf="isFail">{{warnMessage}}</div> <div style="color: red; margin-left: 40px;" *ngIf="isFail2">{{warnMessage2}}</div> <button type="button" class="btn btn-warning" (click)="CreateUser()">註冊</button> </div> <!-- <h5 onclick="show_hide()">註冊帳號</h5> --> <button type="button" class="btn btn-warning" routerLink='/login'>返回登入</button> </div><!-- login end--> <!-- <div > <h1 style="size: 16px;">登入成功</h1> <button type="button" class="btn btn-warning" routerLink="/">logout</button> </div> --> </div><!-- container1 end--> </div><!-- login_page end--> </body> </html> <br><br><br><br><br> ``` # ts ``` import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; const customer_url = "http://localhost:8080/api/customer/"; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.css'] }) export class RegisterComponent implements OnInit { username: string; password: string; isFail: boolean = false; warnMessage: String = '帳戶已經存在'; isFail2: boolean = false; warnMessage2: String = '請輸入帳號或密碼!'; // customer: Object; // customers: Object; // allcustomers: any = []; ngOnInit(): void { // this.CreateUser(); } constructor(private http: HttpClient) { } CreateUser() { //帳號或密碼為空,顯示錯誤訊息 "請輸入帳號或密碼" if (this.username == null || this.password == null) { this.isFail2 = true; } else { this.isFail2 = false; this.http.post(customer_url + this.username, this.username).subscribe(res => { console.log(res) // 判斷帳號有無重複 if (res == true) { console.log("已經存在") this.isFail = true; } else if (res == false) { const c = { username: this.username, password: this.password } console.log(this.username) this.http.post(customer_url + 'all', c).subscribe(d => { // console.log("res", d) window.alert("註冊成功"); this.isFail = false; }) } }) } } } ``` # appcomponent html ``` <!DOCTYPE html> <html lang="en"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script> <body> <!-- Navigation--> <nav class="navbar navbar-expand-lg" style="background-color: #b8aa95;"> <div class="container px-4 px-lg-5"> <a class="navbar-brand" routerLink="" routerLinkActive="active">3C SHOP</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0 ms-lg-4"> <li class="nav-item"><a class="nav-link active" aria-current="page" routerLink="" routerLinkActive="active">首頁</a></li> <!--<li class="nav-item"><a class="nav-link" routerLink="Iphone" routerLinkActive="active">Iphone</a></li> <li class="nav-item"><a class="nav-link" routerLink="iPad" routerLinkActive="active">iPad</a></li>--> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" id="navbarDropdown" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">商品分類</a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <!--<li><a class="dropdown-item">商品分類</a></li> <li> <hr class="dropdown-divider" /> </li>--> <li><a class="dropdown-item" routerLink="Iphone" routerLinkActive="active">Iphone</a></li> <li><a class="dropdown-item" routerLink="iPad" routerLinkActive="active">iPad</a></li> </ul> </li> <li class="nav-item"><a class="nav-link" routerLink="addproduct" routerLinkActive="active">新增商品</a></li> </ul> <div *ngIf="isLogin()"> <button [routerLink]="['/cart']" routerLinkActive="active" class="btn btn-outline-dark" style="margin-right: 10px;"> <i class="bi-cart-fill me-1"></i> Cart <!-- <span class="badge bg-dark text-white ms-1 rounded-pill">0</span> --> </button> </div> <div class="login" *ngIf="!isLogin()"> <button routerLink='/login' type="button" class="btn btn-outline-light me-1">Login</button> </div> <br> <div *ngIf="isLogin()"> <button (click)="logout()" routerLink="/" type="button" class="btn btn-outline-light me-1">Logout</button> Hi, {{userSession}} </div> </div> </div> </nav> <!-- Section--> <router-outlet></router-outlet> <!-- Footer--> <footer class="py-5" style="background-color:#5E5A54;"> <div class="container"> <p class="m-0 text-center text-white">Copyright &copy; 3C SHOP 2023</p> </div> </footer> <!-- Bootstrap core JS--> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script> <!-- Core theme JS <script src="js/scripts.js"></script>--> </body> </html> ``` # appcomponent ts ``` import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { isFail: boolean = false; userSession = sessionStorage.getItem('user'); ngOnInit(): void { this.userSession = sessionStorage.getItem('user'); this.isLogin() } constructor(private http: HttpClient) { } title = 'finallab'; isLogin(){ return sessionStorage.getItem('user')!=null; } logout(){ sessionStorage.removeItem('user'); } } ``` # module ``` import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { BrowserModule } from '@angular/platform-browser'; import {HttpClientModule} from '@angular/common/http'; import {RouterModule,Routes} from '@angular/router'; import { AppComponent } from './app.component'; import { ProductComponent } from './product/product.component'; import { CartComponent } from './cart/cart.component'; import { LoginComponent } from './login/login.component'; import { RegisterComponent } from './register/register.component'; import { AddProductComponent } from './addproduct/addproduct.component'; import { ModifyProductComponent } from './modify-product/modify-product.component'; import { CategoryIpadComponent } from './category-ipad/category-ipad.component'; import { CategoryIphoneComponent } from './category-iphone/category-iphone.component'; const appRoute :Routes=[ {path:'',component: ProductComponent}, {path:'product',component: ProductComponent}, {path:'product/:id/:name/:price/:detail',component: ModifyProductComponent}, {path:'addproduct',component:AddProductComponent}, {path:'cart',component:CartComponent }, {path:'login',component:LoginComponent }, {path:'register',component:RegisterComponent }, {path:'iPad',component:CategoryIpadComponent }, // {path:'iPad/:id/:name/:price/:detail',component: ModifyProductComponent} {path:'Iphone',component:CategoryIphoneComponent } // {path:'Iphone/:id/:name/:price/:detail',component: ModifyProductComponent}, ] @NgModule({ declarations: [ AppComponent, ProductComponent, AddProductComponent, CartComponent, LoginComponent, RegisterComponent, ModifyProductComponent, CategoryIpadComponent, CategoryIphoneComponent, ], imports: [ BrowserModule, HttpClientModule, FormsModule, RouterModule.forRoot(appRoute), ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } ```