第40天~

这个得上一篇:https://ithelp.ithome.com.tw/articles/10258374

看到数量再多按几次会增加.再到cart-status.component.ts档案:

https://ithelp.ithome.com.tw/upload/images/20210821/20119035TRo1V7J3Ff.png

然後也是updateCartStatus按右键修正:
https://ithelp.ithome.com.tw/upload/images/20210821/20119035vomBnhGIGq.png

再修改内容:

https://ithelp.ithome.com.tw/upload/images/20210821/20119035W0C0PCjO6F.png

import { CartService } from './../../services/cart.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-cart-status',
  templateUrl: './cart-status.component.html',
  styleUrls: ['./cart-status.component.css']
})
export class CartStatusComponent implements OnInit {

  totalPrice: number = 0.00;
  totalQuantity: number = 0;

  constructor(private CartService: CartService) { }

  ngOnInit(): void {
    this.updateCartStatus();
  }
  updateCartStatus() {

    this.CartService.totalPrice.subscribe(
      data => this.totalPrice = data

    );


  this.CartService.totalQuantity.subscribe(
    data => this.totalQuantity = data

  );


  }

}

然後再到cart-status.component.html档案:修正{{ totalPrice | currency: 'USD'}}和 {{ totalQuantity}}

<div class="cart-area d-n">
  <a href="shopping-detail.html">
    <div class="total">{{ totalPrice | currency: 'USD'}}
      <span> {{ totalQuantity}}</span>
    </div>
     <i class="fa fa-shopping-cart"  aria-hidden="true"></i>
  </a>
</div>

最原本空的
https://ithelp.ithome.com.tw/upload/images/20210821/20119035cr0GEci35q.png
然後有新增的
https://ithelp.ithome.com.tw/upload/images/20210821/20119035Xj9EyKc2wG.png

  • 把购物车修到更好*

再来到cart.service.ts档案:

找到这段CODE
https://ithelp.ithome.com.tw/upload/images/20210821/20119035IAp7B3gAwl.png

删掉他再修正~tempCartItem => tempCartItem.id === tempCartItem.id持续测试到修正(3个等於)
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Equality_comparisons_and_sameness

严格相等(===)
严格相等比较两个值,而被比较的两个值都不会转换成其他型别。如果值是不同型别,就会被视为不相等。如果两值型别相同但不是数字,若值相同,则为相等。此外,如果两个值皆为数字,只要他们是 NaN 以外的同一值,或者 +0 和 -0,则为相等。

import { CartItem } from './../common/cart-item';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CartService {

  CartItems: CartItem[]=[];

  totalPrice: Subject<number> = new Subject<number>();
  totalQuantity: Subject<number> = new Subject<number>();


  constructor() { }

  addToCart(theCartItem:CartItem){


    let alreadyExistsInCart : boolean = false;
    let existingCartItem: CartItem = undefined;

    if (this.CartItems.length>0){

     existingCartItem = this.CartItems.find( tempCartItem => tempCartItem.id === tempCartItem.id);

      alreadyExistsInCart =(existingCartItem != undefined);
    }

    if (alreadyExistsInCart){
      existingCartItem.quantity++;
    }
    else{
      this.CartItems.push(theCartItem);
    }

    this.computeCartTotals();


  }
  computeCartTotals() {

    let totalPriceValue: number =0;
    let totalQuantityValue: number =0;

    for(let currentCartItem of this.CartItems){
      totalPriceValue += currentCartItem.quantity * currentCartItem.unitPrice;
      totalQuantityValue += currentCartItem.quantity;
    }

    this.totalPrice.next(totalPriceValue);
    this.totalQuantity.next(totalQuantityValue);

    this.logCartData(totalPriceValue, totalQuantityValue);

      }
  logCartData(totalPriceValue: number, totalQuantityValue: number) {

    console.log('Contents of the cart');
    for (let tempCartItem of this.CartItems){
      const subTotalPrice = tempCartItem.quantity * tempCartItem.unitPrice;
      console.log(`name: ${tempCartItem.name}, quantity=${tempCartItem.quantity},unitPrice=${tempCartItem.unitPrice},subTotalPrice=${subTotalPrice}`);
    }

    console.log(`totalPrice: ${totalPriceValue.toFixed(2)}, totalQuantity: ${totalPriceValue}`);
    console.log('----');

  }
}

用chrome 开发者工具可以看到任点都OK

https://ithelp.ithome.com.tw/upload/images/20210822/20119035tHm2HYK1TV.png

让产品细目里的加入购物车的按键也有作用

到product-details.component.html档案-从这句修改开始
https://ithelp.ithome.com.tw/upload/images/20210822/20119035X5s0JNKdnF.png

<div class="detail-section">

 <div class="container-fluid">

  <img src="{{product.imageUrl}}" class="detail-img">

  <h3>{{product.name}}</h3>

  <div class="price">{{product.unitPrice |currency:'USD'}}</div>
  <button (click)="addToCart()" class="btn btn-primary btn-sm" >Add to cart</button>

  <hr>
  <h4>Description</h4>
  <p>{{product.description}}</p>


  <a routerLink="/products" class="mt-5">Back to Product List</a>


 </div>
</div>

到这里的addToCart会反红
https://ithelp.ithome.com.tw/upload/images/20210822/20119035QDqW5YxgIW.png
是因为要去product-details.component.ts 档案新增:

https://ithelp.ithome.com.tw/upload/images/20210822/20119035Kgu4uNur78.png

再到最下面:
https://ithelp.ithome.com.tw/upload/images/20210822/20119035lyNbAt6gRv.png

import { CartService } from './../../services/cart.service';
import { Routes, ActivatedRoute } from '@angular/router';
import { ProductService } from 'src/app/services/product.service';
import { Product } from 'src/app/common/product';
import { Component, OnInit } from '@angular/core';
import { CartItem } from 'src/app/common/cart-item';

@Component({
  selector: 'app-product-details',
  templateUrl: './product-details.component.html',
  styleUrls: ['./product-details.component.css']
})
export class ProductDetailsComponent implements OnInit {

  product:Product = new Product();

  constructor(private ProductService:ProductService,
              private CartService: CartService,
              private route:ActivatedRoute) { }

  ngOnInit(): void {
    this.route.paramMap.subscribe(() =>{
      this.handleProductDetails();
    })
  }
  handleProductDetails() {
    const theProductId:number = +this.route.snapshot.paramMap.get('id');

    this.ProductService.getProduct(theProductId).subscribe(

      data =>{

        this.product = data;
      }
    )

      }

      addToCart(){
        console.log(`Adding to cart: ${this.product.name},${this.product.unitPrice}`);
        const theCartItem = new CartItem(this.product);
        this.CartService.addToCart(theCartItem);



      }



}

用chrome的开发者工具来检查
https://ithelp.ithome.com.tw/upload/images/20210822/20119035EhstoQ1yap.png

这个得下一篇:https://ithelp.ithome.com.tw/articles/10258452


<<:  Day37 参加职训(机器学习与资料分析工程师培训班),ResNet, RNN

>>:  Ruby--Find the Difference

[第15天]理财达人Mx. Ada-持仓部位(库存)(positions)

前言 本文说明持仓部位(库存)(positions)资讯。 程序实作 程序 positions =a...

Day 29 | 关於像素那档事

看到目前为止,能够发现到影像辨识可说是深度学习应用中相当热门且实用的一个项目,然而如果要了解其中的运...

Day15 Combine 02 - Publisher

Publisher 在Combine 中,Publisher 是观察者模式中的Observable,...

什麽是MVC框架? 如何用UML建模?

MVC模式的架构元件被设计用来处理开发中的应用程序的不同方面。MVC设计模式的作用是将表现层与业务逻...

Day2:在Anaconda上安装Tensorflow以及Keras

  上篇明白到目前Tensorflow的状况如何,是时候重新建立环境了,我使用Anaconda建立环...