第42天~

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

到cart.service.spec.ts档案

import { ProductService } from 'src/app/services/product.service';
import { TestBed } from '@angular/core/testing';

import { CartService } from './cart.service';

describe('ProductService', () => {

  beforeEach(() =>
    TestBed.configureTestingModule({}));

  it('should be created', () => {
    const service: ProductService =TestBed.get(ProductService);
    expect(service).toBeTruthy();
  });
});


app.component.spec.ts 档案:

import { TestBed } from '@angular/core/testing';

import { ProductService } from './product.service';

describe('ProductService', () => {
  beforeEach(() => TestBed.configureTestingModule({}));

  it('should be created', () => {
    // tslint:disable-next-line: deprecation
    const service: ProductService = TestBed.get(ProductService);
    expect(service).toBeTruthy();
  });
});

https://ithelp.ithome.com.tw/upload/images/20210826/20119035e5anRMhbFX.png

这里到cart-details.component.html 档案:

<div class="main-content">
  <div class="section-content section-content-p30">
      <div class="container-fluid">

          <table class="table table-bordered">
              <tr>
                  <th width="20%">Product Image</th>
                  <th width="50%">Product Detail</th>
                  <th width="30%"></th>
              </tr>

              <tr *ngFor="let tempCartItem of cartItems">
                  <td>
                      <img src="{{ tempCartItem.imageUrl }}" class="img-responsive" width="150px" />
                  </td>
                  <td>
                      <p>{{ tempCartItem.name }}</p>
                      <p>{{ tempCartItem.unitPrice | currency: 'USD' }}</p>
                  </td>
                  <td>
                      <div class="items">
                          <label>Quantity:</label> {{ tempCartItem.quantity }}
                      </div>

                      <p class="mt-2">Subtotal: {{ tempCartItem.quantity * tempCartItem.unitPrice | currency: 'USD' }}</p>
                  </td>
              </tr>

              <tr>
                  <td colspan="2"></td>
                  <td style="font-weight: bold">
                      <p>Total Quantity: {{ totalQuantity }}</p>
                      <p>Shipping: FREE</p>
                      <p>Total Price: {{ totalPrice | currency: 'USD' }}</p>
                  </td>
              </tr>

          </table>

      </div>
  </div>
</div>

https://ithelp.ithome.com.tw/upload/images/20210826/20119035abgtlNKN1s.png
https://ithelp.ithome.com.tw/upload/images/20210826/20119035rw1ZAdh6VL.png
这里卡在只有选书才能跳转~我来debug一下
https://ithelp.ithome.com.tw/upload/images/20210824/201190357PwmgrhmNv.png

/images/emoticon/emoticon06.gif

目前是加总不准~我再回来debug
QQ
https://ithelp.ithome.com.tw/upload/images/20210826/20119035XGmLB0mqza.png

後来发现是到 cart.service.ts档案的CODE打错了~是theCartItem 而不是tempCartItem:

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 === theCartItem.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: ${totalQuantityValue}`);
    console.log('----');

  }
}

https://ithelp.ithome.com.tw/upload/images/20210826/201190355kxFOZTDTI.png

按再多都会自动加总
https://ithelp.ithome.com.tw/upload/images/20210826/20119035yAilEXshHE.png

再到app.component.html档案

从这里开始改
https://ithelp.ithome.com.tw/upload/images/20210826/20119035Qd2IAsguWp.png

改成
https://ithelp.ithome.com.tw/upload/images/20210826/20119035RuFQHLDcSE.png

再回到cart-details.component.html 档案
https://ithelp.ithome.com.tw/upload/images/20210826/20119035hqBEGLb4pL.png

<div class="main-content">
  <div class="section-content section-content-p30">
      <div class="container-fluid">
       <div *ngIf="cartItems.length > 0">
          <table class="table table-bordered">
              <tr>
                  <th width="20%">Product Image</th>
                  <th width="50%">Product Detail</th>
                  <th width="30%"></th>
              </tr>
              <tr *ngFor="let tempCartItem of cartItems">
                  <td>
                      <img src="{{ tempCartItem.imageUrl }}" class="img-responsive" width="150px" />
                  </td>
                  <td>
                      <p>{{ tempCartItem.name }}</p>
                      <p>{{ tempCartItem.unitPrice | currency: 'USD' }}</p>
                  </td>
                  <td>
                      <div class="items">
                          <label>Quantity:</label> {{ tempCartItem.quantity }}
                      </div>

                      <p class="mt-2">Subtotal: {{ tempCartItem.quantity * tempCartItem.unitPrice | currency: 'USD' }}</p>
                  </td>
              </tr>
              <tr>
                  <td colspan="2"></td>
                  <td style="font-weight: bold">
                      <p>Total Quantity: {{ totalQuantity }}</p>
                      <p>Shipping: FREE</p>
                      <p>Total Price: {{ totalPrice | currency: 'USD' }}</p>
                  </td>
            </tr>

          </table>
      </div>
  </div>
</div>
</div>

然後再来写如果购物车是空的要显示:
https://ithelp.ithome.com.tw/upload/images/20210826/20119035R684r271ed.png

<div class="main-content">
  <div class="section-content section-content-p30">
      <div class="container-fluid">
       <div *ngIf="cartItems.length > 0">
          <table class="table table-bordered">
              <tr>
                  <th width="20%">Product Image</th>
                  <th width="50%">Product Detail</th>
                  <th width="30%"></th>
              </tr>
              <tr *ngFor="let tempCartItem of cartItems">
                  <td>
                      <img src="{{ tempCartItem.imageUrl }}" class="img-responsive" width="150px" />
                  </td>
                  <td>
                      <p>{{ tempCartItem.name }}</p>
                      <p>{{ tempCartItem.unitPrice | currency: 'USD' }}</p>
                  </td>
                  <td>
                      <div class="items">
                          <label>Quantity:</label> {{ tempCartItem.quantity }}
                      </div>

                      <p class="mt-2">Subtotal: {{ tempCartItem.quantity * tempCartItem.unitPrice | currency: 'USD' }}</p>
                  </td>
              </tr>
              <tr>
                  <td colspan="2"></td>
                  <td style="font-weight: bold">
                      <p>Total Quantity: {{ totalQuantity }}</p>
                      <p>Shipping: FREE</p>
                      <p>Total Price: {{ totalPrice | currency: 'USD' }}</p>
                  </td>
            </tr>

          </table>
      </div>

     <div *ngIf="cartItems.length ==0" class="alert alert-waring col-md-12" role="alert">

      购物车是空的

     </div>



  </div>
</div>
</div>

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


<<:  Ruby幼幼班--Best Time to Buy and Sell Stock

>>:  [C#] 取得证交所台股价格的 3 种实用方法(附范例下载)

Django #1-3 套件管理工具pip pipenv poetry

1. pip Python 原生套件管理工具 venv 虚拟环境 install python -m...

Day 30 Docker 的使用安全

若要长期稳定的使用服务,了解其安全性是必要的。毕竟世上没有 100% 安全的软硬体,总是会存在一些漏...

Day 29: Detective 简介与操作

What is Amazon Detective? Detetive能够帮助你调查资安事件发生的根本...

PHP:isset()小知识

前言 常常在要使用ORM model或seesion资料之前要确认他们是否为空(Null)。例如se...

[想试试看JavaScript ] 物件 建构式

昨天做了一个 player 的物件范例 var player=new Object(); playe...