首页 > 解决方案 > 调用 Angular 服务导致无休止的循环

问题描述

我正在从 CartComponent.html 模板调用 getSubtotal() 方法,如下所示:

<div class="col-lg-4 bg-white text-right">
   <p class="font-bold">
      {{cartService.getSubtotal() | currency:'USD':'symbol-narrow'}}
   </p>
</div>

这是 CartService 的 getSubtotal 方法,它现在只记录 cartItems 对象:

public getSubtotal() {
   var subtotal:number = 0;

   console.log('getSubtotal() ', this.cartItems)
   // for(let item of this.cartItems) {
   //   subtotal += this.getItemPrice(item);
   // }

   return subtotal;
 }

显然 getSubtotal 方法被无休止地调用。它循环打印:

getSubtotal()  (13) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

标签: angular

解决方案


推荐阅读