1

I have an angular application with Firebase. I want to change the value of an firebase item. Everytime the total KM changes it needs to be set to the right value. so this is my services:

    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;

  }

Now for some reason, when i add a ride everything is fine, but the second time everything goes wrong.

for example the first time the foreach runs i get (after firebase has already 5 items):

0{
0: 5,
1: 5,
2: 5,
3: 5,
4: 5,
}

After i run the foreach 1 time my object list is like this: 0{ 0: 5, 1: 5, 2: 5, 3: 5, 4: 5, 5: 5, }

After add a new value the second time and further the foreach does this:

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,

        }

Is there some one who can help me? I think it's a wrong configuration in the foreach but can't find out where.

Thanks for you help!

1 Answer 1

3

this.uniqueRides.push(ride.km); is just pushing additional items into the array.

Either check to see if the ride is included .includes

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

or clear the array out every time. this.uniqueRides = []

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man, it works. Fine to have some community with heroes who can help you!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.