循环通过可观察数组并更新计算值

时间:2018-03-26 13:46:23

标签: javascript rxjs observable

我有一个Observable数组,我希望能够拥有一个包含来自数组内容的计算值的公共值。

@Injectable()
export class PaymentsProvider {

  total: number = 0;

  private payments = new BehaviorSubject(<Payment[]>[]);
  payments$: Observable<Payment[]> = this.payments.asObservable();

  constructor() {

    console.log("init payments service")
    this.total = 0
    this.payments$.subscribe( payments => {
       for (let payment of payments) {
         this.total += payment.amount
       }
    })    
  }
}

这样做,我可以从其他组件调用this.paymentsService.total,但是如果我离开页面组件并导航回来,则值加倍,即使payments数组有没有改变。

我应该以不同的方式计算这个吗?

1 个答案:

答案 0 :(得分:1)

this.total = 0;放入您订阅的回调

&#13;
&#13;
    
    this.payments$.subscribe( payments => {
       this.total = 0
       for (let payment of payments) {
         this.total += payment.amount
       }
    })    
&#13;
&#13;
&#13;