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

Is there a way to dynamically change the options in a dropdown menu using Angular?

I am facing an issue where the values in my dropdown list are changing to null when I click on the form. The add function is working correctly, but this update problem is bothering me. Can anyone provide assistance? Below is the snippet of my HTML code: ...

Challenge with Routing in Angular 2

I'm dealing with a route setup like this: path: 'something/:id/somethingElse' In my header.component.html, I need to include a link to this page. I tried the following approach: <a routerLink="['something',myIdThatIsDynamicO ...

The AngularJS 2 TypeScript application has been permanently relocated

https://i.stack.imgur.com/I3RVr.png Every time I attempt to launch my application, it throws multiple errors: The first error message reads as follows: SyntaxError: class is a reserved identifier in the class thumbnail Here's the snippet of code ...

Error: Name 'AudioDecoder' could not be located

In my current project using React and TypeScript with Visual Studio Code 1.69.2 and Node 16.15.1, I encountered an issue. I am attempting to create a new AudioDecoder object, but I keep getting an error message stating "Cannot find name 'AudioDecoder ...

Wait for the nested request to finish before returning the Observable

There are a pair of POST-requests within this function: function addArticle(request: IArticle) { const requestPath = `${this.backendUrl}/articles`; return this.http .post<IResponse<IArticleApiContract>>(requestPath, getArticleApiContra ...

I am interested in incorporating apexcharts and ng-apexcharts into Angular 18 with server-side rendering (SSR)

I am facing an issue while trying to integrate apexcharts and ng-apexcharts in Angular 18 with SSR. The problem I encounter is: The error "window is not defined" is thrown at node_modules/apexcharts/dist/apexcharts.common.js (c:/Users/lakhm/Desktop/cod ...

The latest release of Next JS 13 is experiencing issues with Next Auth functionality

I need assistance. Ever since I started using the Next 13 app directory, it's been quite challenging. Most of the code that worked on the previous version is not compatible with this one, including Next Auth. I'm trying to connect my Firebase to ...

Retrieve functions with varying signatures from another function with precise typing requirements

My code includes a dispatch function that takes a parameter and then returns a different function based on the parameter value. Here is a simplified version: type Choice = 'start' | 'end'; function dispatch(choice: Choice) { switch ...

"The CanActivate guard leads to a redirection to the root path upon initial loading, causing the router-outlet to fail

Recently, I encountered an issue with my SPA configuration that involves the AuthGuard. The setup is such that if a user is not logged in, they are redirected to an error page. However, when the user is logged in, specific routes are accessible. Here’s a ...

"Enhance your web development with TypeScript and react-select

I find myself in a peculiar predicament. Currently, I am immersing myself in learning TypeScript and here is a brief overview of what transpired so far: const [selectedBankCode , setSelectedBankCode] = useState<string | undefined>(); const [selecte ...

Issue with Angular 2's event emitter malfunctioning

I have a dashboard component and a bottom-nav component. When the setting icon in the bottom-nav component is clicked, I want an alert to appear in the parent dashboard component. Here is the code: dashboard.component.ts ===== html part ====== <div cl ...

Issue NG8002: Unable to link to 'FormGroup' as it is not recognized as a property of 'form' in Angular 9

I recently created a brand new Angular 9 application with a submodule. Here are my app.modules.ts: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from & ...

Utilizing generic union types for type narrowing

I am currently attempting to define two distinct types that exhibit the following structure: type A<T> = { message: string, data: T }; type B<T> = { age: number, properties: T }; type C<T> = A<T> | B<T>; const x = {} as unkn ...

What is the solution for resolving array items in a GraphQL query?

I am facing an issue with my graphql Query, specifically in trying to retrieve all the fields of a Post. { getSpaceByName(spaceName: "Anime") { spaceId spaceName spaceAvatarUrl spaceDescription followin ...

Developing an Angular project may result in an overflow of memory

After attempting to construct an Angular project on a Linux server with the -aot flag, I encountered an error. Despite upgrading my instance to a higher CPU core, increasing RAM, and enabling a SWAP partition, the error persisted and even occurred more rap ...

Setting the ariaLabel value in TypeScript is a straightforward process that involves defining the

In my TypeScript React application, I am attempting to dynamically set the ariaLabel value. However, ESLint is flagging an error: Property 'ariaLabel' does not exist on type 'HTMLButtonElement'. I have tried various types but none of t ...

Loading dynamic components asynchronously in Vue 3 allows for improved performance and enhanced user experience

My goal is to dynamically display components based on their type. Here's how I'm approaching it: I have several similar components that should show different content depending on their type. Using the defineAsyncComponent method, I can easily im ...

Passing props from pages to components in NextJS: A guide

My nextjs-application has a unique folder structure: components -- layouts --- header.tsx --- index.tsx pages -- index.tsx -- [slug].tsx In the [slug].tsx file, I utilize graphql to fetch data and set the props accordingly: export default ...

Angular error: Unable to locate a distinguishing object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables like Arrays

Greetings everyone! I am currently exploring the openWeb API to retrieve some data. While I was able to successfully display the data in the console, I'm facing difficulties when it comes to actually presenting it on the screen. ERROR Error: Cannot f ...

Unleash the potential of a never-ending expansion for grid cells on Canvas

ts: templateStyle = { display: 'grid', 'grid-template-columns': 'calc(25%-10px) calc(25%-10px) calc(25%-10px) calc(25%-10px)', 'grid-template-rows': '150px auto auto', 'grid-gap ...