【发布时间】:2019-02-01 11:55:35
【问题描述】:
我有一个带有 Firebase 的 Angular 应用程序。我想更改 firebase 项目的值。每次总 KM 发生变化时,都需要将其设置为正确的值。所以这是我的服务:
countKm(){
this.totalKmRef = this.db.list(this.uid + '/rides');
this.totalKm$ = this.totalKmRef.valueChanges();
this.totalKm$.subscribe(res=> this.getAllRides(res));
}
getAllRides(res){
this.rides = res;
this.rides.forEach(ride =>{
this.uniqueRides.push(ride.km);
})
this.totalKm = this.uniqueRides.reduce(this.sum);
localStorage.setItem("totalKm", this.totalKm);
}
sum(a, b){
return a += b;
}
现在由于某种原因,当我添加行程时一切正常,但第二次出现问题。
例如我第一次运行 foreach 时(在 firebase 已经有 5 个项目之后):
0{
0: 5,
1: 5,
2: 5,
3: 5,
4: 5,
}
在我运行 foreach 1 次后,我的对象列表是这样的: 0{ 0:5, 1:5, 2:5, 3:5, 4:5, 5:5, }
在第二次添加一个新值之后,foreach 会进一步这样做:
0{
0: 5,
1: 5,
2: 5,
3: 5,
4: 5,
5: 5,
6: 5,
7: 5,
8: 5,
9: 5,
10: 5,
11: 5,
12: 5,
}
有人可以帮助我吗?我认为这是 foreach 中的错误配置,但找不到位置。
感谢您的帮助!
【问题讨论】:
标签: javascript arrays angular foreach reduce