添加到购物车在Angular中不起作用

时间:2018-07-25 08:20:17

标签: angular

我已经设置了产品ID,后端需要提供选项和数量。如果我将这样的值硬编码:

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

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

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

Product-details.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;
}

1 个答案:

答案 0 :(得分:0)

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

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