angular - 添加到购物车在 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>
<input value="1" name="Quantity" #Quantity="ngModel" [(ngModel)]="cart.Quantity">
<button type="button" data-toogle="tooltip" title="Increment" (click)="increaseQuantity(selectedproduct)" class="btn-increment"> + </button>
</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;
}
解决方案
您的承诺没有返回正确的对象(https://stackoverflow.com/a/41810325/3387996),您需要添加它
async addProductToCart()
{
const response = await this.cartService.postCart(this.cart);
if (response) {
this.cart.push(response.json());
}
}
推荐阅读
- kubernetes-helm - 在 HELM values.yaml 中引用之前声明的值
- kendo-ui - 当某些列中有大量数据时,无法从 Kendo 网格中删除一行
- sharepoint - 根据另一列的值隐藏 SharePoint 列表列
- php - Laravel 中的命名空间别名
- javascript - 如何将子组件的状态传递给父组件?
- python-3.x - 如何将看起来像列表的字符串转换为浮点列表?
- react-native - 从 createBottomTabNavigator 导航到 createStackNavigator 页面不起作用
- python-3.x - 插值和插补有什么区别?
- kubernetes - 使用 istio 通过外部代理引导 http 流量
- mysql - node_modules/mysql/lib/protocol/Parser.js:437 抛出错误;// 重新抛出非 MySQL 错误