每次我按下添加购物车按钮时,我都会尝试在产品模板上分配产品数量

问题描述

每次点击添加到购物车按钮时,我想在product-list.component.html中呈现产品数量计数。它没有显示您在我的代码中看到的数量,我称之为getQuantity方法

product.component.html

       <div class="card" *ngIf="product.payload.val().title "  style="width: 18rem;">
        <img [src]="product.payload.val().imageUrl" class="card-img-top" *ngIf="product.payload.val().imageUrl"  alt="...">
        <div class="card-body">
          <h5 class="card-title">{{product.payload.val().title}}</h5>
          <h5 class="card-title">{{product.payload.val().category}}</h5>
          <p class="card-text">{{product.payload.val().price | currency: symbol-narrow}}</p>
        </div>
        <div class="card-footer">
          <button *ngIf="getQuantity() === 0; else updateQuantity"
           (click)="addToCart()" class="btn btn-primary"> Add to cart</button>
        </div>
        <ng-template #updateQuantity>
       <div class="row no-gutters">
         <div class="col-2"(click)="removeFromCart()" class="btn btn-primary">-</div>
         <div class="col text-center">  {{getQuantity()}} in cart</div>
         <div class="col-2"(click)="addToCart()" class="btn btn-primary">+</div>
       </div>

        </ng-template>
      </div>  

product-list.component.ts

import { Component,OnInit,Input } from '@angular/core';
import{ShoppingCartService} from '../../../shared/services/shopping-cart.service'

@Component({
  selector: 'product-list',templateUrl: './product-list.component.html',styleUrls: ['./product-list.component.scss']
})


export class ProductListComponent  {

@Input('product') product: any = [];
@Input('shoppingCart') shoppingCart;

  constructor(private cartService: ShoppingCartService ){ }
  
  addToCart(){
    this.cartService.addToCart(this.product);
  }

  getQuantity(){
    if (!this.shoppingCart ) {return 0; }; 
    let item = this.shoppingCart.items[this.product.key];
    return item ? item.qauntity:  0;
  }

  removeFromCart(){
    this.cartService.removeFromCart(this.product);
  }

}

在这里,我调用了getQuantity方法来检查购物车中是否有东西,如果没有的话,则每次按下添加到购物车按钮时都会增加

shopping-cart.service


import { Injectable } from '@angular/core';
import { AngularFireDatabase,AngularFireObject } from 'angularfire2/database';
import { IShoppinCart } from '../models/IShoppingCart';

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


  constructor(private db: AngularFireDatabase) { }

  private create() {
    return this.db.list('/shopping-carts/').push({
      dateCreated: new Date().getTime()
    });
  }

  private async getOrCreateCartId() {
    let cartId = localStorage.getItem('cartId');
    if (cartId) return cartId;


    let result = await this.create();
    localStorage.setItem('cartId',result.key);
    return result.key;
  }

  async getcart(): Promise<AngularFireObject<IShoppinCart>> {
    let cartID = await this.getOrCreateCartId();
    return this.db.object('/shopping-carts/' + cartID);

  }

  private getItem(cartId: string,productID: string) {
    return this.db.object('/shopping-carts/' + cartId + '/items/' + productID);
  }

  async addToCart(product) {
    this.updateToCart(product,1);
  }

  async removeFromCart(product) {
    this.updateToCart(product,-1);
  }

  async updateToCart(product,quantityState) {
    let cartId = await this.getOrCreateCartId();

    let items$ = this.getItem(cartId,product.key);

    items$.snapshotChanges().take(1).subscribe((item: any) => {
      if (item.payload.exists()) {
        items$.update({ quantity: item.payload.val().quantity + quantityState });
      }
      else {
        items$.update({
          product: {
            title: product.payload.val().title,price: product.payload.val().price,category: product.payload.val().category,imageUrl: product.payload.val().imageUrl
          },quantity:(item.payload.exists() ? item.payload.val()['quantity'] : 0) + 1
        });
      }
    })

  }

}

product.component.ts

import { Component,OnDestroy } from '@angular/core';
import { ProductService } from 'src/app/shared/services/product.service';
import { ActivatedRoute } from '@angular/router';
import 'rxjs/add/operator/switchMap';
import { CategoryService } from 'src/app/shared/services/category.service';
import { Subscription } from 'rxjs';
import { ShoppingCartService } from 'src/app/shared/services/shopping-cart.service';

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


  products: any[] = [];
  filteredProducts: any[] = [];
  categories$;
  category = '';
  subscription: Subscription;
  cart;

  constructor(
    private route: ActivatedRoute,private productService: ProductService,private cartService: ShoppingCartService

  ) {
    this.subscription = this.productService
      .get().switchMap(products => {
        this.products = products;
        return this.route.queryParamMap;
      })
      // read values of query string
      .subscribe(params => {
        this.category = params.get('category');
        this.filteredProducts = (this.category) ?
          this.products.filter(p => p.payload.val().category === this.category) : this.products;
      })

  }
  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }

  async ngOnInit() {

    this.subscription = (await this.cartService.getcart()).snapshotChanges().subscribe(cart => { this.cart = cart.payload.val();
       //console.log(cart) 
      })

  }


}

product-list.component.html

           <div class="card" *ngIf="product.payload.val().title "  style="width: 18rem;">
        <img [src]="product.payload.val().imageUrl" class="card-img-top" *ngIf="product.payload.val().imageUrl"  alt="...">
        <div class="card-body">
          <h5 class="card-title">{{product.payload.val().title}}</h5>
          <h5 class="card-title">{{product.payload.val().category}}</h5>
          <p class="card-text">{{product.payload.val().price | currency: symbol-narrow}}</p>
        </div>
        <div class="card-footer">
          <button *ngIf="getQuantity() === 0; else updateQuantity"
           (click)="addToCart()" class="btn btn-primary"> Add to cart</button>
        </div>
        <ng-template #updateQuantity>
       <div class="row no-gutters">
         <div class="col-2"(click)="removeFromCart()" class="btn btn-primary">-</div>
         <div class="col text-center">  {{getQuantity()}} in cart</div>
         <div class="col-2"(click)="addToCart()" class="btn btn-primary">+</div>
       </div>

        </ng-template>
      </div>


    
  

在控制台日志中,我看到该商品已添加到购物车,但未反映在模板中

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...