【问题标题】:angular foreach problems when adding new items添加新项目时的角度问题
【发布时间】: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


    【解决方案1】:

    this.uniqueRides.push(ride.km); 只是将其他项目推入数组。

    检查是否包含行程.includes

    this.rides.forEach(ride => {
       if(!this.uniqueRides.includes(ride)) {
          this.uniqueRides.push(ride.km);
       }
    })
    

    或每次清除数组。 this.uniqueRides = []

    【讨论】:

    • 谢谢,它的工作原理。很高兴有一些可以帮助你的英雄社区!
    猜你喜欢
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多