我在这里处理一个问题,至少对我来说相当复杂。我有一个产品详情页,这是应该显示产品数量,细节,产品数量的增量和减量。我面临的问题是,当我单击递增或递减图标时,它不会显示产品数量,而是显示"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>发布于 2021-09-29 11:22:39
根据TypeScript - Variables的说法,
在TypeScript中声明变量的类型语法是在变量名后面加上冒号(:),后跟变量类型。
如果在变量之后使用冒号(:),则必须指定类型。
quantity: number = 1;或
将数值直接赋值给变量。该变量将被视为number类型。
quantity = 1;https://stackoverflow.com/questions/69375159
复制相似问题