【发布时间】:2025-12-18 19:05:01
【问题描述】:
我在这里处理的问题至少对我来说相当复杂。我有一个产品详细信息页面,它应该显示产品数量、详细信息、产品数量的增量和减量。面临的问题是,当我单击增量或减量图标时,它不显示产品数量,而是显示“NaN”而不是产品数量,并且我的代码编辑器中没有错误。如果有人能指出我的错误并且整天都在做这件事,我将不胜感激。提前致谢。
Product-Details.Component.ts
import { Component, OnInit } from '@angular/core';
import { IProduct } from 'src/app/shared/models/product';
import { ShopService } from '../shop.service';
import { ActivatedRoute } from '@angular/router';
import { BreadcrumbService } from 'xng-breadcrumb';
import { BasketService } from 'src/app/basket/basket.service';
@Component({
selector: 'app-product-details',
templateUrl: './product-details.component.html',
styleUrls: ['./product-details.component.scss']
})
export class ProductDetailsComponent implements OnInit {
product: IProduct;
quantity: 1;
constructor(private shopService: ShopService, private activateRoute: ActivatedRoute,
private bcService: BreadcrumbService, private basketService:BasketService) {
this.bcService.set('@productDetails', '');
}
ngOnInit(): void {
this.loadProduct();
}
addItemToBasket() {
this.basketService.addItemToBasket(this.product, this.quantity);
}
incrementQuantity() {
this.quantity++;
}
decrementQuantity() {
if(this.quantity > 1) {
this.quantity--;
}
}
loadProduct() {
this.shopService.getProduct(+this.activateRoute.snapshot.paramMap.get('id')!).subscribe(product => {
this.product = product;
this.bcService.set('@productDetails', product.name)
}, error => {
console.log(error);
});
}
}
Product-Details.Component.html
<div class="container mt-5">
<div class="row" *ngIf="product">
<div class="col-6">
<img src="{{product.pictureUrl}}" alt="{{product.name}}" class="img-fluid w-100">
</div>
<div class="col-6">
<h3>{{product.name}}</h3>
<p style="font-size: 2em;">{{product.price | currency}}</p>
<div class="d-flex justify-content-start align-items-center">
<i (click)="decrementQuantity()" class="fa fa-minus-circle text-warning mr-2" style="cursor: pointer; font-size: 2em;"></i>
<span class="font-weight-bold" style="font-size: 1.5em;">{{quantity}}</span>
<i (click)="incrementQuantity()" class="fa fa-plus-circle text-warning mx-2" style="cursor: pointer; font-size: 2em;"></i>
<button (click)="addItemToBasket()" class="btn btn-outline-primary btn-lg ml-4">Add to Cart</button>
</div>
</div>
<div class="row mt-5">
<div class="col-12 ml-3">
<h4>Description</h4>
<p>{{product.description}}</p>
</div>
</div>
</div>
</div>
【问题讨论】:
-
将
quantity类型指定为数字。例如quantity: number = 1;,或quantity = 1;而不是quantity: 1;。 -
非常感谢,已经解决了
标签: angular typescript