update the data source of the material table inside the subscription

Seeking guidance for updating a MatTable datasource within an Angular application. The current Typescript code involves fetching data from an API using AdminService, iterating over the results to make additional API calls for more information about a fleet.

The existing method successfully updates the datasource without any issues, even though there are complexities involved in acquiring the supplementary data.

Your insights and assistance on this matter would be highly appreciated.

refresh(): void {
    const data = {};
    const that = this;
    this.adminService.fleets(data).subscribe(result => {

      that.fleetTableData = [];

      result.forEach(function (fleetObject){

        if (typeof fleetObject.fleetTotals === 'undefined'){
          fleetObject.fleetTotals = {};
          fleetObject.fleetTotals.totalVehicles = 0;
          fleetObject.fleetTotals.totalActiveVehicles = 0;
          fleetObject.fleetTotals.totalStatusTestedVehicles = 0;
        }

        that.fleetTableData[fleetObject.fleetId] = fleetObject;

        that.adminService.vehicles(
          {fleetId: fleetObject.fleetId}
        ).subscribe(result2 => {

          result2.forEach(function (vehicleForFleet) {
            var fleetId = vehicleForFleet.fleetId;
            that.fleetTableData[fleetId].fleetTotals.totalVehicles = (that.fleetTableData[fleetId].fleetTotals.totalVehicles + 1);
            if (typeof vehicleForFleet.commissioning !== 'undefined') {
              if (vehicleForFleet.commissioning.commissionStatus === 'tested') {
                that.fleetTableData[fleetId].fleetTotals.totalStatusTestedVehicles = (that.fleetTableData[fleetId].fleetTotals.totalStatusTestedVehicles + 1);
              }
              if (vehicleForFleet.commissioning.commissionStatus === 'active') {
                that.fleetTableData[fleetId].fleetTotals.totalActiveVehicles = (that.fleetTableData[fleetId].fleetTotals.totalActiveVehicles + 1);
              }
            }
          });
        });
      });

      that.dataSource.data = new MatTableDataSource(that.fleetTableData);
      that.dataSource.sort = that.sort;
      console.log(that.fleetTableData);
    });

  }

Answer №1

After examining the code, it appears that this.datasource is already a MatTableDatasource. In that case, you can simply assign this.fleets to the .data property instead of creating a new MatTableDatasource.

this.dataSource.data = that.fleetTableData;

Answer №2

When looking at your code example, there are a couple of key strategies to consider:

  1. Avoid nesting subscribe() methods in RxJS, as this can cause issues. It's best practice to have only one subscribe() for better code organization.
  2. Rather than executing logic within subscribe(), utilize RxJS "operators" to handle the data manipulation. This will also help eliminate the need for nested subscribe().

Here is a recommended approach:

this.adminService.fleets(data).pipe(
  map(result=>{
    // Define and retrieve necessary data for adminService.vehicles
  }),
  switchMap(fleetId=>this.adminService.vehicles(fleetId)),
  map(result2=>{
    // Implement logic to define and update this.dataSource for your table
  })
).subscribe()

The map() operator allows you to transform emitted values into new values.

Similarly, the switchMap() function operates like map(), but it enables returning a new observable (such as the vehicles method with parameters from the initial observable).

Lastly, use the map() operator again to process the value emitted by adminService.vehicles() and update the state property this.dataSource.

Answer №3

Encountered a similar issue while dealing with a mat-table, and I resolved it using the following method.

this.dataTable = 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

How to Use ngFor to Create a Link for the Last Item in an Array in Angular 7

I need help with adding a link to the last item in my menu items array. Currently, the menu items are generated from a component, but I'm unsure how to make the last item in the array a clickable link. ActionMenuItem.component.html <div *ngIf= ...

We discovered the synthetic attribute @onMainContentChange. To properly integrate this feature into your application, make sure to include either "BrowserAnimationsModule" or "NoopAnimationsModule"

I am working with two modules: AppModule and AFModule: app.module.ts import { NgModule } from '@angular/core'; ... ... import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/ ...

Steps for registering an Angular application on a Eureka server

I'm trying to integrate my Angular application with a Spring Cloud Eureka server. I came across the eureka-js-client library, but I'm unsure about where to place the configuration settings. Additionally, there are methods like client.start() and ...

Sass encountered an issue when trying to import using the "~" symbol from the node_modules directory

I am currently developing a single-page web application using Angular 6, and I recently integrated the ngx-toast library into my project. However, I encountered an issue when trying to load the libraries by adding the following Sass code with the "~" symb ...

What is the best way to validate the Click outside directive in Angular applications?

Exploring the click-outside directive for testing purposes. It seems that there is an issue with ignoring a specific div element while clicking outside. import { Directive, ElementRef, Output, EventEmitter, HostListener } from '@angular/core'; ...

Error Encountered | Invalid Operation: Unable to access attributes of undefined (referencing 'CodeMirror')

Error image on chrome Using Next.js 13 Encountering an error on Google Chrome, seeking a solution to fix it or possibly just ignore it. Not utilizing Codemirror and prefer not to use it either. Tried troubleshooting methods: Deleting ".next","node_ ...

How come the information I receive when I subscribe always seems to mysteriously disappear afterwards?

I've been working on a web project using Angular, and I've run into an issue with my code that's been causing problems for a while now. The problem lies in fetching data from a server that contains translations: getTranslations(): Observab ...

Generics in Typescript implemented for a React component that accepts an array of records along with an array of

I am currently working on developing a straightforward typed react component designed to display a table from an array of objects. The input data is structured as follows: // array of records containing data to render in the table data = [ { one: 1, ...

After successfully installing @angular/localize, running npm update or npm install could result in a dependency error

I am looking to implement @angular/localize in my Angular application. Currently, I have a newly created NestJS backend integrated with an Angular frontend within an Nx monorepo. Upon attempting to install the package using npm install @angular/localize, ...

The Excel Match function is experiencing issues when used in conjunction with the MS-Graph API

Recently, I've encountered an issue with sending a match-function post request to an Excel workbook using the MS-Graph API. Instead of receiving the value of the first column that contains the lookup value, I'm getting the value from the second c ...

Tips on refreshing asset information within a live Angular application

I am currently managing an Angular project on a web server. The server houses python scripts that run periodically to generate a .json file. This latest version of the .json file replaces the existing one in the assets folder of the project (dist/test/asse ...

Hover Effect for 3D Images

I recently came across an interesting 3D Hover Image Effect that I wanted to implement - https://codepen.io/kw7oe/pen/mPeepv. After going through various tutorials and guides, I decided to try styling a component with Materials UI and apply CSS in a differ ...

What steps do I need to take to update Oceania to Australia on Google Maps?

While incorporating the Google Maps API into Angular, an issue arises when zooming out completely: https://i.stack.imgur.com/oZRut.png The label is displaying "Oceania" instead of "Australia". Is there a feasible method to modify this discrepancy? ...

There seems to be an issue with gulp as it is not functioning properly and the version information is

Currently, I am working on a project and have made the decision to utilize gulp for watching and transpiling Typescript files. Below are the steps I followed to set everything up: All of these actions were performed within the main directory of my projec ...

Utilizing Typescript Generics in Arrow Function to Combine Two Arguments

For instance, I am working with this code in a .tsx file extension const Add = <T,>(arg0: T, arg1: T): T => arg0 + arg1; const A = Add(1, 2); const B = Add('1', '2') However, I am encountering an issue, as there is an error m ...

Tips for referencing functions in TypeScript code

In regard to the function getCards, how can a type be declared for the input of memoize? The input is a reference to a function. import memoize from "fast-memoize"; function getCards<T>( filterBy: string, CardsList: T[] = CardsJSON.map((item, i ...

Modifying one input can impact other input elements without any form of direct connection between them

Below is the HTML code snippet: <tr *ngFor="let row of formData; let i = index" [attr.data-index]="i"> <td *ngFor="let rowdata of formData[i]; let j = index" [attr.data-index]="j"> <input type="checkbox" name="row-{{i}}-{{j}}" [ ...

Enhancing Application Performance Through Next.js Development

I'm currently working on an application using next.js and I am looking to implement code splitting in order to reduce the bundle size and load pages on demand. Unfortunately, I have not been able to find a way to do this without specifying routes. Fo ...

The 'id' property is not found within the 'Order[]' type

Encountering a perplexing issue in my HTML where it keeps showing an error claiming that the 'id' property does not exist on type Order[] despite its clear existence The error message displayed: Property 'id' does not exist on type &ap ...

Is it possible to utilize Webpack 5's ChunkGroup API with several entries?

I am encountering an error message when attempting to upgrade from Webpack 4 to Webpack 5. The error states: Module.entryModule: Multiple entry modules are not supported by the deprecated API (Use the new ChunkGroup API) I have searched for information o ...