Local variables are now being refreshed with every modification in the data stored in Cloud Firestore

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.

Answer №1

To reset the counter in the observable, consider adding a value through this code:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a sortable and filterable table in NG-ZORRO using Ant Design

I am currently facing an issue with implementing filters and sorters for all columns in my application, which uses the ng-zorro-antd table component. The challenge arises because the table data is dynamic. Please refer to the snippet of my current code be ...

Workspace watch mode does not update Typescript definitions

Greetings to all who are reading this, I have created a React micro-frontend project using SPA v5.9, Webpack v5.75, Babel-loader v9.1, Ts-loader v9.4, and Yarn workspace v3.5. The project structure is very basic: Root SPA => Package Root Application S ...

What are the best practices for effectively using RxJs subscriptions?

I'm looking for some advice on how to handle Angular and RxJs mechanics. I have server-side pagination set up on my backend and three components on the frontend: a data list, filters, and a pagination component. How can I subscribe to two streams (pag ...

Customizing the Global Error Handler in Angular

Our project utilizes a global error handler to manage errors. However, we have encountered a unique scenario where we need to handle a specific case separately but are unable to do so. The global error handler is configured in the app.module.ts: { provide: ...

Transferring information between two components in separate Angular 4 modules

Within my application, I have defined two modules named AppModule and UserModule. I am currently encountering an issue with data sharing between the AppComponent and the LoginComponent (which belongs to the UserModule). Below is a snippet of app.componen ...

Discovering Child Elements in Angular 2 with @ViewChild and CSS Selectors

I'm looking to update the style of the second paragraph using either the nth-child() selector or by a specific class: import { Component, ViewChild } from '@angular/core'; @Component({ selector: 'my-app', template: ` <d ...

A function that has a declared type other than 'void' or 'any' is required to return a value

I'm facing an issue in my angular2 application where a service is sending a get request to a specific URL. Below is the code snippet of the service: import {Http} from '@angular/http'; import {Observable} from 'rxjs/Observable'; i ...

Is there a beginner's pack or trial version available for utilizing TypeScript with IBM Cloud Functions / OpenWhisk?

While working on developing actions in IBM Cloud Functions, I have been primarily using Node.js / Javascript and Python for coding. However, I haven't come across specific instructions on how to incorporate TypeScript into IBM Cloud Functions. I am c ...

Leverage the compiler API to perform type inference

Exploring TypeScript's compiler API for basic type inference has proven to be a challenge with limited helpful information found in documentation or online searches. My goal is to create a function inferType that can determine and return the inferred ...

Dealing with the 'UNIFIED_TEST_PLATFORM' issue while trying to compile an Ionic android app that utilizes tesseract.js and capacitor core

I recently set up an Ionic Angular project and integrated Capacitor to access native code functionalities. My project utilizes tesseract.js, as well as Capacitor core and camera plugins. However, I encountered an error while building the Android project: ...

Custom JSX element failing to include children during addition

I have created a unique component in JSX, like this: const CustomComponent = ({content}) => { return <div className={content}></div>; } I am using it as follows: <CustomComponent content={"xyz"}> <p>Some additio ...

Why is TS1005 triggered for Redux Action Interface with an expectation of '=>'?

I'm finding it difficult to identify what's causing this issue, as shown in the esLint error from Typescript displayed in the screenshot below: https://i.stack.imgur.com/pPZa7.png Below is the complete code, which consists of actions for redux. ...

Utilizing the array.map method to access the key of an object within an array of arrays in TypeScript

Can I utilize array.map in TypeScript to apply a function with the parameter being the key of an object within an array? I have an array containing objects which have keys 'min' and 'max'. I am looking to use something like someArrayFun ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

Having trouble retrieving the URL from the router in Angular 2?

Whenever I try to access the URL using console.log(_router.url), all it returns is a / (forward slash). Here is the code snippet in question: constructor( private el: ElementRef, private _auth:AuthenticationService, @Inject(AppStore) private ...

Automatic verification of OTP in Ionic 3

Seeking assistance for implementing auto OTP verification in a project I am working on. After the user enters their phone number, I have come across some examples for Ionic 1 with Angular 1 online. However, I am specifically looking for examples using Io ...

The image source failed to load the image using the function

Initially, I set up a sandbox to work on this issue: https://codesandbox.io/s/naughty-almeida-u66mlt?file=/src/App.js The main problem arises when the requested image fails to display after the function is called and the URL is returned. Here are my atte ...

Tips for managing Razorpay responses in Angular 2

I'm currently in the process of finalizing my payment transaction through RazorPay Payment gateway, and I've attempted to do so as shown below: var options = { "key": "XXX", "amount": 100, "name": "Ezshipp", "description": this.it ...

Exploring TypeScript Module Importation and WebPack Integration

Struggling with WebPack's injection of imported dependencies for a TypeScript project. The first challenge is getting TypeScript to recognize the imported module. In the header.ts file, there is a declaration of a module nested under vi.input, export ...

Exploring the capabilities of renderOption within Material-UI's AutoComplete functionality

Hey there, I've been pondering a question lately and could really use some help. I've been trying to set up my autocomplete feature to display a label in the options while having a different value. After doing some research, I learned about usin ...