【问题标题】:Updated local variables every data change in cloud firestoreCloud Firestore 中的每个数据更改都更新了局部变量
【发布时间】:2019-10-06 01:24:00
【问题描述】:

每次在云 Firestore 中设置数据时,我都无法设置本地变量。例如,在局部变量调用count_vehicle 中,该值是基于云Firestore 中数据的具有特定条件的值的计数。例如,在运行程序count_vehicle = 4 后,当我更改firestore 中的数据时,count_vehicle 变量在经过一些计算后必须为3,而不是count_vehicle become 7 (3+4)。为了解决这个问题,我打算在开始计算之前设置count vehicle = 0。这是我的代码

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()
    }
    }
  }

谢谢你的帮助。对不起我的英语

【问题讨论】:

    标签: angular typescript firebase rxjs google-cloud-firestore


    【解决方案1】:

    您应该能够添加一个值以将计数器重置为可观察对象,例如:

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

    【讨论】:

      猜你喜欢
      • 2019-07-12
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-04
      • 2023-03-30
      • 2018-05-08
      • 1970-01-01
      相关资源
      最近更新 更多