首页 > 解决方案 > 添加到购物车在 Angular 中不起作用

问题描述

我已经在后端设置了产品 ID、选项和数量。如果我像这样硬编码值:

{ ProductId : 1, option: 'string', Quantity: 1 }

有用。但是,当我尝试使用以下代码单击“添加到购物车”按钮时,它不起作用。

任何人都可以帮助解决此问题。

产品详细信息.html:

<input type="hidden" name="ProductId" #ProductId="ngModel" [(ngModel)]="cart.ProductId">
<div class="card">
    <div class="card-header">
        <h3 class="price-details-header" name="Option" #Option="ngModel" [(ngModel)]="cart.Option"></h3>
    </div>
    <div class="col-md-6" >
        <button type="button" data-toogle="tooltip" title="Decrement" (click)="decreaseQuantity(selectedproduct)" class="btn-decrement">- </button>&nbsp;
        <input  value="1" name="Quantity" #Quantity="ngModel" [(ngModel)]="cart.Quantity">&nbsp;
        <button type="button" data-toogle="tooltip" title="Increment" (click)="increaseQuantity(selectedproduct)" class="btn-increment"> + </button>&nbsp;&nbsp;  
    </div>
    <div class="col-md-6">
        <a href="" class="btn btn-success btn-lg" (click)="addProductToCart()" routerLink="/cart">
        <i class="fa fa-shopping-cart fa-lg"></i> Add to Cart</a>
    </div>

Product-details.component.ts 文件:

export class ProductDetailsComponent implements OnInit {
    cart : Cart[];
    selectedproduct : any; 

    async addProductToCart() 
    {
        const response = await this.cartService.postCart(this.cart);

        if (response) {
            console.log(response);
        }
    }

Cart.service 文件:

async postCart(cart: Cart[]) {
    const response = await this.httpClient.post('myURL', cart,
        { observe: 'response', withCredentials: true }).toPromise();

    return response;
}

标签: angular

解决方案


您的承诺没有返回正确的对象(https://stackoverflow.com/a/41810325/3387996),您需要添加它

   async addProductToCart() 
   {
    const response = await this.cartService.postCart(this.cart);
    if (response) {
      this.cart.push(response.json());
    }
   }

推荐阅读