iT邦幫忙

0

第44天~

Tzu 2021-08-26 22:12:45871 瀏覽
  • 分享至 

  • xImage
  •  

這個得上一篇:https://ithelp.ithome.com.tw/articles/10258532

這裡要來寫減少和移除:

從 cart-details.component.html檔案.增加


     <button (click)="decrementQuantity(tempCartItem)" class="btn btn-primary btn-sm">
     

https://ithelp.ithome.com.tw/upload/images/20210829/20119035q4TPHbMctM.png

再到 cart-details.component.ts檔案.增加方法:

https://ithelp.ithome.com.tw/upload/images/20210831/201190351A7S5133YR.png

選方法:
https://ithelp.ithome.com.tw/upload/images/20210831/20119035I4bfmYc3KC.png

mport { CartService } from 'src/app/services/cart.service';


import { Component, OnInit } from '@angular/core';
import { CartItem } from 'src/app/common/cart-item';

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

  cartItems: CartItem[]=[];
  totalPrice: number =0;
  totalQuantity: number =0;




  constructor(private cartService:CartService ) { }

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

    this.cartItems = this.cartService.cartItems;

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

    );

    this.cartService.totalQuantity.subscribe(

      data => this.totalQuantity = data

    );

    this.cartService.computeCartTotals();




  }

  incrementQuantity(theCartItem: CartItem){
    this.cartService.addToCart(theCartItem);
  }
  decrementQuantity(theCartItem: CartItem){
    this.cartService.decrementQuantity(theCartItem);
  }
}

再到 cart.service.ts檔案

剪下這裡:
https://ithelp.ithome.com.tw/upload/images/20210831/201190358zsv5mEs0E.png

移到最下面:
https://ithelp.ithome.com.tw/upload/images/20210831/20119035nkGKVpeUYT.png

然後開始改寫程式碼:

https://ithelp.ithome.com.tw/upload/images/20210831/20119035tWTUjLoBBQ.png

再新增方法
https://ithelp.ithome.com.tw/upload/images/20210831/201190350gSzlwBCoE.png

修改程式碼:

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('----');

  }


  decrementQuantity(theCartItem: CartItem) {

    theCartItem.quantity--;

    if (theCartItem.quantity === 0){
      this.remove(theCartItem);
    }
    else{
      this.computeCartTotals();
        }
  }
  remove(theCartItem: CartItem) {

    const itemIndex = this.cartItems.findIndex( tempCartItem => tempCartItem.id === theCartItem.id);

    if (itemIndex >-1) {
      this.cartItems.splice(itemIndex,1);

      this.computeCartTotals();
    }
    }
}


到購物車發現按-會變少
https://ithelp.ithome.com.tw/upload/images/20210831/20119035DI0RFmfHku.png

再到 cart-details.component.html檔案.增加REMOVE按鈕:

https://ithelp.ithome.com.tw/upload/images/20210831/20119035oHpce4VPDG.png

https://ithelp.ithome.com.tw/upload/images/20210831/20119035Dc6dBDob6Z.png

建立會作動的語法:
https://ithelp.ithome.com.tw/upload/images/20210831/20119035Ic2yxL8eFi.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>

                           <div class="row no-gutters">
                            <div class="col">
                             <button (click)="incrementQuantity(tempCartItem)" class="btn btn-primary btn-sm">

                             <i class="fas fa-plus"></i>

                             </button>

                            </div>

                          <div class="col ml-4 mr-2">

                            {{ tempCartItem.quantity}}

                          </div>

                          <div class="col">
                            <button (click)="decrementQuantity(tempCartItem)" class="btn btn-primary btn-sm">
                            <i class="fas fa-minus"></i>
                            </button>
                           </div>

                          <div class="col-8"></div>

                           </div>
                      </div>

                      <button (click)="remove(tempCartItem)" class="btn btn-primary btn-sm mt-2">Remove</button>

                      <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>

再到cart-details.component.ts 檔案增加語法:

https://ithelp.ithome.com.tw/upload/images/20210831/20119035GfSoOqwXzx.png

import { CartService } from 'src/app/services/cart.service';


import { Component, OnInit } from '@angular/core';
import { CartItem } from 'src/app/common/cart-item';

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

  cartItems: CartItem[]=[];
  totalPrice: number =0;
  totalQuantity: number =0;




  constructor(private cartService:CartService ) { }

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

    this.cartItems = this.cartService.cartItems;

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

    );

    this.cartService.totalQuantity.subscribe(

      data => this.totalQuantity = data

    );

    this.cartService.computeCartTotals();




  }

  incrementQuantity(theCartItem: CartItem){
    this.cartService.addToCart(theCartItem);
  }
  decrementQuantity(theCartItem: CartItem){
    this.cartService.decrementQuantity(theCartItem);
  }

  remove(theCartItem:CartItem){
    this.cartService.remove(theCartItem);
  }
}



發現可以移除REMOVE 物件

這個得下一篇:https://ithelp.ithome.com.tw/articles/10258602


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言