【发布时间】:2020-11-19 14:23:40
【问题描述】:
我的 Angular 应用程序中有一个购物车服务,当列表中的每个项目被添加到购物车时,我试图在列表上的每个项目上制作一个加减数量按钮,当一个项目首次添加到购物车时,它的数量是 1然后用户通过按 +- 可以更改它的数量,问题是当我将数量更改为 3 然后我将进入购物车页面并删除该项目,返回产品页面并按“添加到cart" 它设置的商品数量为 3 而不是 1,即使它已从购物车中删除。
这是我的代码:
CartService.ts:
addToCart(plu: Plu): void {
this.carrello.plu.push(product);
this.cartTotal(); // function which save the cart to localstorage
}
getQta(plu: Plu): number { // getting qta to be set if the cart exist in products list
const index = this.carrello.plu.indexOf(plu);
if (index !== -1) {
return this.carrello.plu[index].qta;
}
return 0;
}
updateQta(plu: Plu, qta: number): void {
const index = this.carrello.plu.indexOf(plu);
const oldQta = this.carrello.plu[index].qta;
const newQta = oldQta + qta;
if (newQta === 0){ // if quantity is 0 removing object from cart array
this.carrello.plu.splice(index);
this.cartTotal();
return;
}
this.carrello.plu[index].qta = newQta; // else updating it with new quantity
this.cartTotal();
}
然后我调用这些方法的 HTML 看起来像这样
<div *ngFor="let plu of plus">
<button
class="btn btn-block btn-primary"
[hidden]="getQta(plu) !== 0" // if never added to cart product show button Add to cart
(click)="addToCart(plu, $event)"
>
Aggiungi al carrello
</button>
<div
class="input-group"
[hidden]="getQta(plu) === 0" // else showing +- buttons for quantity
>
<div class="input-group-prepend">
<button class="btn btn-primary font-weight-bold" (click)="updateQta(plu, -1)">
-
</button>
</div>
<input
type="number"
class="form-control text-center"
disabled
[min]="plu.um === 'PZ' ? 1 : 0.001"
[step]="plu.um === 'PZ' ? 1 : 0.001"
[value]="
plu.um != 'PZ'
? (getQta(plu) | number: '1.3-3':'en-US')
: getQta(plu)
"
/>
<div class="input-group-append">
<button class="btn btn-primary font-weight-bold" (click)="updateQta(plu, 1)">
+
</button>
</div>
</div>
</div>
</div>
然后方法只是在 ProductComponent.ts 中重新创建,如下所示:
addToCart(plu: Plu, event: Event): any {
event.preventDefault();
event.stopPropagation();
this.cartService.addToCart(plu);
this.showToast();
}
updateQta(plu: Plu, qta: number): void {
this.cartService.updateQta(plu, qta);
}
getQta(plu: Plu): number {
return this.cartService.getQta(plu);
}
但是,一旦产品从购物车页面中删除,我将返回产品列表,我更改数量的每个 Plu 的原始对象将其作为数量而不是 1,所以我实际上看到“添加到购物车按钮”,但一旦点击它会显示最后选择的数量,因为它已被设置为原始对象...
编辑:
这是一个带有购物车服务的 ProductComponent 的小示例,您可以在将商品添加到购物车并再次添加后看到(如果商品存在于购物车服务中,我将添加 qta 而不是再次将其推送到数组) 新增项目的 qta 甚至在变化
【问题讨论】:
-
发生这种情况是因为当您在页面之间导航时正在重新加载应用程序,因此服务会被重置。您可以通过更改在页面/部分之间导航的方式或使用
localStorage来解决此问题,以便在您导航时恢复某种“保存”。 -
@JacopoSciampi 但实际上因为我正在更改购物车服务数组中对象的数量,为什么甚至产品列表数组也会受到该更改的影响?问题是..
-
就像在调试中一样,当我单击 updateQta 时,plu 应该保持不变,而每次单击 updateQta 时它的数量都会发生变化,即使我正在更改它的服务数量而不是原始数组中的数量..
-
你能创建一个stackBlitz吗?
-
@ХристиянХристов 添加。
标签: angular typescript