我有一个使用 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 中的错误配置,但找不到位置。
谢谢你的帮助!
最佳答案
this.uniqueRides.push(ride.km);
只是将额外的项目插入数组。
要么检查行程是否包含.includes
this.rides.forEach(ride => {
if(!this.uniqueRides.includes(ride)) {
this.uniqueRides.push(ride.km);
}
})
或者每次都清空数组。 this.uniqueRides = []
关于javascript - 添加新项目时的angular foreach问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54479007/