Tips for Decreasing Query Time with MatTable and MatTableDataSource

When working with my firestore database, I am trying to query documents and display them while also calculating the total value of a specific column (promiAmount).

I have successfully displayed the values in a mat table, but I'm struggling to calculate the sum of a particular column (promiAmount).

Despite trying various methods, I keep ending up with an undefined result. It seems like I'm missing a step somewhere, but I can't seem to figure it out.

Here is the model I am working with:

export class PromisoryModel {
    customerAccountNo: string;
    customerName: string;
    customerNo: string;
    transactionDate: string;
    promiFlag:number;
    promiAmount: number;
}

Actual Data from Firestore

{
  "2vnLBK4qGBd4ZNbPz9aq": {

    "customerAccountNo": "100-PDQ-12-17",
    "customerName": "TEST, CUSTOMER 1",
    "customerNo": 17,
    "promiAmount": 1667,
    "promiFlag": 3,
    "transactionDate": "2022-02-15"
  },
  "CcK8Ju8ANOM561UyGPPf": {
    "customerAccountNo": "100-PDQ-12-17",
    "customerName": "TEST, CUSTOMER 1",
    "promiAmount": 1667,
    "promiFlag": "3",
    "transactionDate": "2022-02-15"
  },

Component TypeScript Code:

import { Component, OnInit, ViewChild } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/compat/firestore';
import { Observable} from 'rxjs';
import { PromisoryModel } from 'src/app/models/promisory.model';

@Component({
  selector: 'app-members',
  templateUrl: './members.component.html',
  styleUrls: ['./members.component.scss']
})

export class MembersComponent implements OnInit {
  private PromisorryCollection : AngularFirestoreCollection<PromisoryModel>;
  promissory: Observable<PromisoryModel[]>;

  constructor(public afs: AngularFirestore) {}

  // declarations
  queryName: any;
  promiList: PromisoryModel[];
  getCsrBadge: any;

  
  queryDetails() {
    this.PromisorryCollection = this.afs.collection('promisory',
    ref => ref
    .where('customerName','==', this.queryName)
    .orderBy('transactionDate','desc')
    )
   this.promissory = this.PromisorryCollection.valueChanges();
   this.promissory.subscribe(
      (data) => (this.dataPromiSource = new MatTableDataSource(data),  
      )
   )
  }
}
  

Attempt 1: Result is undefined

this.PromisorryCollection = this.afs.collection('promisory',
    ref => ref
    .where('customerName','==', this.queryName)
    .orderBy('transactionDate','desc')
    )
   this.promissory = this.PromisorryCollection.valueChanges();
   this.promissory.subscribe(
      (data) => (this.dataPromiSource = new MatTableDataSource(data),
      
      this.getCsrBadge = (data).reduce((acc, cur)=> {
        return acc + cur.promiAmount
      },0)
      )
   )

   console.log(this.getCsrBadge)

Attempt 2: Result is undefined

this.PromisorryCollection = this.afs.collection('promisory',
    ref => ref
    .where('customerName','==', this.queryName)
    .orderBy('transactionDate','desc')
    )
   this.promissory = this.PromisorryCollection.valueChanges();
   this.promissory.subscribe(
      (data) => (this.dataPromiSource = new MatTableDataSource(data),
      this.promiList = (data),
      this.getCsrBadge = this.promiList.reduce((acc, cur)=> {
        return acc + cur.promiAmount
      },0)
      )
   )

Attempt 3: result is undefined

 this.PromisorryCollection = this.afs.collection('promisory',
    ref => ref
    .where('customerName','==', this.queryName)
    .orderBy('transactionDate','desc')
    )
   this.promissory = this.PromisorryCollection.valueChanges();
   this.promissory.subscribe(
      (data) => (this.dataPromiSource = new MatTableDataSource(data),
      this.dataPromiSource.filter = this.queryName.trim().toLowerCase(),
      this.getCsrBadge = this.dataPromiSource.filteredData.map( amount => amount.promiAmount).reduce((acc,cur) => acc + cur,0)
      )
   )
   
   console.log(this.getCsrBadge)

Attempt 4: result is undefined

this.PromisorryCollection = this.afs.collection('promisory',
    ref => ref
    .where('customerName','==', this.queryName)
    .orderBy('transactionDate','desc')
    )
   this.promissory = this.PromisorryCollection.valueChanges();
   this.promissory.subscribe(
      (data) => (this.dataPromiSource = new MatTableDataSource(data),
      data.filter = this.queryName.trim().toLowerCase(),
      this.getCsrBadge = this.dataPromiSource.filteredData.map( amount => amount.promiAmount).reduce((acc,cur) => acc + cur,0)
      )
   )
   
   console.log(this.getCsrBadge)

Answer №1

Through various experiments and with the guidance of @priyashree's reference, it was discovered that we were inadvertently passing empty data to our array. (Apologies for overlooking this mistake due to inexperience)

In our original Second Attempt, we were simply passing our subscription data/observable to our mat-table datasource.

The Second Attempt works perfectly if we adjust the order as follows:

this.PromisorryCollection = this.afs.collection('promisory',
    ref => ref
    .where('customerName','==', this.queryName)
    .orderBy('transactionDate','desc')
    )
   this.promissory = this.PromisorryCollection.valueChanges();
   this.promissory.subscribe(
      (data) => (
      this.promiList = (data),
      this.getCsrBadge =this.promiList.reduce((acc, cur)=> {
        return acc+ cur.promiAmount
      },0),
      this.dataPromiSource = new MatTableDataSource(data))
   )

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

The name '__DEV__' is not discoverable at the moment

While working with the mobx library in my project, I encountered an issue after installing it using npm. Upon exploring the mobx/src/error.ts file within the node_modules folder, I came across a compile time error on line 78: const errors: typeof niceError ...

Obtain Value from Function Parameter

In my Angular project, I have a function that is called when a button is clicked and it receives a value as an argument. For example: <button (click)="callFoo(bar)">Click Me!</button> The TypeScript code for this function looks like ...

Site breaks down post transition to Angular Universal (SSR)

Apologies in advance for the ambiguous title, I didn't want to make it too lengthy. So here's my issue: I have a confirmation page that appears after the user completes a payment on a third-party gateway (like PayPal). The page redirects back to ...

Exploring the functionality of Angular's Material Virtual Scroll and incorporating the scrollToIndex method

Is there a way to manage the scrollToIndex (virtual scroll) if my list is not loaded during the ngAfterViewInit lifecycle? I need to trigger the scroll to a specific index when redirecting from another page, which happens in the ts file. My objective is to ...

Error encountered when using Angular Material date-time picker

I encountered an error in the console when trying to use the Angular Material datetime picker. Although it functions correctly, my tests failed due to this error. https://www.npmjs.com/package/@angular-material-components/datetime-picker <mat-form-fiel ...

Create an HTML button on the homepage that directs users to the "about" page

I've been struggling to make a button in my Ionic app navigate to a different page upon clicking. Despite being new to Ionic, I've spent hours trying to solve this issue. Below is the HTML code in home.page.html: <ion-header> &l ...

Utilize localStorage.getItem() in conjunction with TypeScript to retrieve stored data

Within my codebase, I have the following line: const allGarments = teeMeasuresAverages || JSON.parse(localStorage.getItem("teeMeasuresAverages")) || teeMeasuresAveragesLocal; Unexpectedly, Typescript triggers an alert with this message: Argument ...

Best location for the classes of the Domain Model suggested

Currently, I am delving into Angular 2 and making use of angular-cli for creating components and services. Adhering to the directory structure suggested by angular-cli (view screenshot below), I am uncertain about where to include domain model objects like ...

Tips for adding Google Tag Manager to a popup within a Chrome extension?

I have successfully developed a chrome extension. In the popup HTML, I added the Google Tag Manager script and a noscript iframe like this: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Signals< ...

Typescript fails to identify the parameter type of callbacks

I am facing a challenge with the function below and its callback type: type Callbacks = { onSuccess: (a: string) => void; }; function myFunction(event: string, ...args: [...any, Callbacks]) { } The function works correctly except for one issue - ...

Using sl-vue-tree with vue-cli3.1 on internet explorer 11

Hello, I am a Japanese individual and my proficiency in English is lacking, so please bear with me. Currently, I am using vue-cli3.1 and I am looking to incorporate the sl-vue-tree module into my project for compatibility with ie11. The documentation menti ...

The Vue property I customized in my component is not being recognized by VSCode(Vetur)

I've successfully implemented a plugin in Vue by declaring it in a main.ts file, defining its type in a plugin.d.ts file, and utilizing it in a component.vue file. Although the compilation is error-free, I am encountering an issue with VSCode intellis ...

Can we determine the data type of a value within a class instance by utilizing a function to retrieve it?

Is it feasible to create a function that maintains typing and functions in the same way as this: class Example { someNumber:number = 1; someString:string = "test"; } const example = new Example(); const value = example.someNumber; // typ ...

Is it possible to create a tuple with additional properties without needing to cast it to any type?

To accommodate both array and object destructuring, I have defined the following `Result` type: type Errors = Record<string, string | null>; type Result = [Errors, boolean] & { errors: Errors; success: boolean }; I attempted to create a result of t ...

How to disable time selection in owl-date-time picker for Angular 6 inputs

To install the ng-pick-datetime package, use the following command: npm install ng-pick-datetime --save I recently incorporated the Owl Date Time Picker into my project. You can find more information about it here. <input [owlDateTimeTrigger]="dt10" [ ...

Exploring TypeScript Generics and the Concept of Function Overloading

How can I create a factory function that returns another function and accepts either one or two generic types (R and an optional P) in TypeScript? If only one generic type is provided, the factory function should return a function with the shape () => ...

What is the best way to organize objects based on their timestamps?

I am faced with the task of merging two arrays of objects into a single array based on their timestamps. One array contains exact second timestamps, while the other consists of hourly ranges. My goal is to incorporate the 'humidity' values from t ...

Firebase Error: The creator key was not defined, which cannot be passed as undefined in JSON. Instead, use null

Currently, I'm working on a project using angularFire 0.8.2. The project is actually based on thinkster.io's angular-firebase tutorial. However, I've encountered a hurdle when trying to create a custom user profile and access the data within ...

Displaying the focus icon on the active tab using Angular Material

I am currently utilizing Angular material to dynamically generate tabs in my HTML code. I'm trying to display a drop arrow icon on the active or selected tabs, but I am facing some challenges with the implementation. Below is the code snippet I have ...

Setting up default QueryParamsHandling in Angular

I have successfully developed an angular 9 application and implemented localization using @ngx-translate. To ensure that the app changes locale based on the 'lang' query parameter, I configured it accordingly. @Component({ selector: 'app- ...