简体   繁体   中英

Updated local variables every data change in cloud firestore

I have problem to set my local variables every time the data in cloud firestore. In local variable call count_vehicle for example, the value is count of value with spesific condition based on data in cloud firestore. For examples after run the program the count_vehicle = 4 , when i changes the data in firestore, the count_vehicle variables must 3 after some calculation, but instead the count_vehicle become 7 (3+4) . To solve this, my intention is to set count vehicle = 0 before start calculation. This is my code

dashboard.component.ts

//import section

//component declaration section



export class DashboardComponent implements OnInit {
  items = any[];
  count_vehicle: number =0;

  constructor(public service: FireService) {
  }
  startAnimationForLineChart(chart){
  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()
    }
    }
  }

Thanks if you can help.sorry for my english

您应该能够添加一个值来将计数器重置为observable,例如:

this.service.getVehicle().merge(Rx.Observable.from([ -1*this.count_vehicle ])).pipe(...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM