Having trouble maintaining the accuracy of my local variables in sync with changes to the data in cloud firestore. Specifically, in my local variable called count_vehicle
, the value represents a count based on specific conditions from the data in cloud firestore. For example, after running the program, if count_vehicle = 4
, and then I update the data in firestore which should result in count_vehicle
being recalculated to be 3, it ends up being 7 (3 + 4) instead. To address this issue, I am considering initializing count vehicle = 0
before starting the calculation process. Below is my code snippet:
dashboard.component.ts
// Sections for imports
// Component declaration section
export class DashboardComponent implements OnInit {
items = any[];
count_vehicle: number = 0;
constructor(public service: FireService) {
}
ngOnInit() {
this.service.getVehicle().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
if(data.value > 300){
this.count_vehicle++;
}
return {id, .. data};
}))
)
.subscribe(res => {
this.items = res;
console.log(res)
})
}
}
fire.service.ts
import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class FireService {
constructor(public db : AngularFirestore) { }
getVehicle(): Observable<any[]>{
return this.db.collection('/recent_sensor_data').snapshotChanges()
}
}
}
Appreciate any help provided. Apologies for any language-related shortcomings.