我有一个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
数组有没有改变。
我应该以不同的方式计算这个吗?
答案 0 :(得分:1)
将this.total = 0;
放入您订阅的回调
this.payments$.subscribe( payments => {
this.total = 0
for (let payment of payments) {
this.total += payment.amount
}
})
&#13;