【问题标题】:How to update product quantity after adding product to cart?将产品添加到购物车后如何更新产品数量?
【发布时间】:2019-08-07 11:59:03
【问题描述】:

我正在开发一个使用 Angular 和 django 开发的购物车项目。我想在添加产品时更新产品数量。但是现在刷新页面时会更新数量。

到目前为止,我已经尝试过以下代码。

Home.Component.ts:

    async ngOnInit() {
    await this.getUpdatedCart();}

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

     async getUpdatedCart() {
      await this.cartService.getCart(this.products);
      this.subscription =  this.cartService.updatedCart
      .subscribe(cart => {
       this.cart = cart;
       console.log('cart', this.cart);
     });
  }

shopping-cart.services.ts:

   updatedCart = new BehaviorSubject<any>('');

    async getCart(product) {
    const cartId = JSON.parse(localStorage.getItem('cartId'));
    if (cartId) {
       this.http.get(this.globalService.baseUrl + 'shopping-cart/' + cartId + '/').subscribe(data => this.updatedCart.next(data));
    }}

product-card.component.ts:

     export class ProductCardComponent {
     @Input('product') product;
     @Input('shopping-cart') shoppingCart;

     constructor(private cartService: ShoppingCartService,
              private homeComponent: HomeComponent) {
    }

    async addToCart(product) {
    await this.cartService.addProductToCart(product);
    await this.homeComponent.getUpdatedCart();
  }

    getQuantity() {
     if (!this.shoppingCart) {
      return 0;
     }
     const item = this.shoppingCart.carts;
     for (let i = 0; i < item.length; i++) {
      if (item[i].product === this.product.id) {
        return item[i].qty;
      }
    }
    return 0;}}

product-card.component.html:

  <div class="card-footer">
   <button (click)="addToCart(product) " class="btn btn-primary btn- 
    block">Add to cart</button>
       <div>{{getQuantity() }}</div>
    </div>
   </div>

我希望当用户单击“添加到购物车”按钮时,数量将被更新。 但是点击两次按钮后数量会更新。

【问题讨论】:

    标签: django angular6


    【解决方案1】:

    在这种情况下使用 主题 (Example)。在 shopping-cart.services.ts 中创建服务并从那里获取购物车数据。您将在订阅该购物车时获得更新的购物车。

    【讨论】:

    • 正如你所建议的,我已经更新了我的代码。但仍然没有变化。我想我在某处犯了错误@Aarti
    • 您还可以使用 Angular 的 ngDoCheck 生命周期并在其中检查购物车变量。虽然,这种方法是不推荐的,因为它会检查每个事件的变化。但在你的情况下,它可能会起作用。
    猜你喜欢
    • 1970-01-01
    • 2012-06-09
    • 2012-12-05
    • 2016-02-28
    • 2014-11-21
    • 2011-12-19
    • 2015-03-31
    • 1970-01-01
    相关资源
    最近更新 更多