mat-table dataSource is not functioning properly with REST API integration

I'm facing an issue while trying to populate a Material Table with data.

My model Block has fields such as id, date, etc. The API call is made in data.service and the function getAllBlock() fetches the blocks. I tested this in the app.component.html file and it worked fine.

document-list.component.ts

import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { DataService } from '../data.service';
import { Block } from '../models/block.model';

@Component({
    selector: 'app-document-list',
    templateUrl: './document-list.component.html',
    styleUrls: ['./document-list.component.sass']
})
export class DocumentListComponent implements OnInit {
    blocks: Block[];
    //DataSource and columns for DataTable
    displayedColumns: string[] = ['Id', 'Date', 'Data', 'Hash', 'PreviousHash'];
    dataSource = new MatTableDataSource<Block>(this.blocks);

    //Filter (search)
    applyFilter(filterValue: string) {
        this.dataSource.filter = filterValue.trim().toLowerCase();
    }

    constructor(private dataService: DataService) { }

    ngOnInit(){
        return this.dataService.getAllBlock()
        .subscribe(data => this.blocks = data);
    }
}

document-list.component.html

<div class="content-table">
    <mat-form-field>
        <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
    </mat-form-field>

    <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
        <!-- ID Column -->
        <ng-container matColumnDef="Id">
            <th mat-header-cell *matHeaderCellDef>ID</th>
            <td mat-cell *matCellDef="let element"> {{element.Id}} </td>
        </ng-container>

        <!-- Date Column -->
        <ng-container matColumnDef="Date">
            <th mat-header-cell *matHeaderCellDef>Timestamp</th>
            <td mat-cell *matCellDef="let element"> {{element.Date}} </td>
        </ng-container>

        <!-- Data Column -->
        <ng-container matColumnDef="Data">
            <th mat-header-cell *matHeaderCellDef>Data</th>
            <td mat-cell *matCellDef="let element"> {{element.Data}} </td>
        </ng-container>

        <!-- Hash Column -->
        <ng-container matColumnDef="Hash">
            <th mat-header-cell *matHeaderCellDef>Hash</th>
            <td mat-cell *matCellDef="let element"> {{element.Hash}} </td>
        </ng-container>

        <!-- Previous Hash -->
        <ng-container matColumnDef="PreviousHash">
            <th mat-header-cell *matHeaderCellDef>PrevHash</th>
            <td mat-cell *matCellDef="let element"> {{element.PreviousHash}} </td>
        </ng-container>
        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </table>
</div>

I need assistance on how to add data to the table successfully. Can someone guide me on what might be going wrong with my implementation?

Answer №1

When dealing with asynchronous data, the initial value of this.blocks is undefined. It is important to create the dataSource only after this.blocks has been defined, which happens once you subscribe to the getAllBlock() method. Using return in this context is unnecessary since you are simply extracting data from the subscribe method. Instead, just directly call getAllBlock().

Here's how your revised code should appear:

dataSource: MatTableDataSource<Block>;

ngOnInit() {
    this.dataService.getAllBlock().subscribe(data => {
        this.blocks = data
        this.dataSource = new MatTableDataSource<Block>(this.blocks);
    });
}

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

Issues with Angular routing in Fuse administrator and user interfaces

I am encountering an issue with navigating routes for admin and user roles, where the user role has limitations compared to the admin role. <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.1/angular.min.js"></script> const ...

You cannot use ca.select(....).from function after the code has been minified

My Angular application utilizes squel.js and functions correctly in development mode. However, upon building the app for production and attempting to use it, I encounter the following error message: ca.select(...).from is not a function This error ref ...

Enhance the annotation of JS types for arguments with default values

Currently, I am working within a code base that predominantly uses JS files, rather than TS. However, I have decided to incorporate tsc for type validation. In TypeScript, one method of inferring types for arguments is based on default values. For example ...

Issues with sending emails through Nodemailer in a Next.js project using Typescript

I'm currently working on a personal project using Nodemailer along with Next.js and Typescript. This is my first time incorporating Nodemailer into my project, and I've encountered some issues while trying to make it work. I've been followin ...

Tips for uploading images, like photos, to an iOS application using Appium

I am a beginner in the world of appium automation. Currently, I am attempting to automate an iOS native app using the following stack: appium-webdriverio-javascript-jasmine. Here is some information about my environment: Appium Desktop APP version (or ...

Guide to creating a one-to-one object literal map with a different value type using a function return without explicitly defining the return type

At the moment, I have successfully managed to combine the keys and values of each object literal that is passed into a function. For example: interface StaticClass<T = any> { new (...args: any[]): T } type RecordOfStaticClasses = Record<string, ...

Looking to change the pagination arrow icons in Angular's mat-paginator to something different. Let's replace them with new icons

Looking to customize the arrows icons on an Angular mat-paginator for a unique design. For more information on mat-paginator, please see this link: https://material.angular.io/components/paginator/overview I attempted to locate a way to change the icon by ...

Best method for integrating widget scripts in Angular 5

I am in the process of developing an Angular 5 application and I have encountered a challenge while trying to integrate a widget into one of the components. Following the guidance provided in this particular question, I attempted to add the widget as inst ...

Transform JSON object array into a different format

Can anyone help me with an issue I am facing with checkboxes and arrays in Angular 2? I have checkboxes that capture the value "role". Each role is stored in an array called "selectedRoles". However, when I try to console.log this.selectedRoles, I get str ...

Can someone explain the inner workings of the Typescript property decorator?

I was recently exploring Typescript property decorators, and I encountered some unexpected behavior in the following code: function dec(hasRole: boolean) { return function (target: any, propertyName: string) { let val = target[propertyName]; ...

Update the response type for http.post function

I've implemented a post method using Angular's HttpClient. While attempting to subscribe to the response for additional tasks, I encountered the following error: Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{}, ...

The express application's GET route is causing a "Cannot GET" error to be thrown

I am managing different types of pages: the main root page (/) today's chapter page (/929 OR /929/) which eventually redirects to /929/<CHAPTER> where <CHAPTER> is a natural number between 1 to 929 individual chapter pages (/929/<CHAP ...

Ionic 2 fails to navigate when using [navPush]

Today I delved into working with Ionic 2 and was making good progress. I had successfully implemented navigation across 3-4 pages, but then something suddenly broke that has left me scratching my head. Now whenever I try to navigate to another page, I kee ...

Refresh a page automatically upon pressing the back button in Angular

I am currently working on an Angular 8 application with over 100 pages (components) that is specifically designed for the Chrome browser. However, I have encountered an issue where the CSS randomly gets distorted when I click the browser's back button ...

Caution: The `id` property did not match. Server: "fc-dom-171" Client: "fc-dom-2" while utilizing FullCalendar in a Next.js environment

Issue Background In my current project, I am utilizing FullCalendar v5.11.0, NextJS v12.0.7, React v17.0.2, and Typescript v4.3.5. To set up a basic calendar based on the FullCalendar documentation, I created a component called Calendar. Inside this comp ...

Error: The AppModule is missing a provider for the Function in the RouterModule, causing a NullInjectorError

https://i.stack.imgur.com/uKKKp.png Lately, I delved into the world of Angular and encountered a perplexing issue in my initial project. The problem arises when I attempt to run the application using ng serve.https://i.stack.imgur.com/H0hEL.png ...

Building a personalized React component poses challenges when working with MUI REACT interfaces

I am looking to develop a unique component that will display two different elements, an icon, and a title. However, I seem to be encountering errors from TypeScript regarding the declaration of my interface. The error message reads: Property 'map&apos ...

The state of dynamically created Angular components is not being preserved

My current task involves dynamically creating multiple components to be placed in a table. The code successfully achieves this objective, but the state seems to be getting jumbled up at the level of the dynamically generated components. When a component is ...

Nested HTTP requests in Angular using RxJS: Triggering component update after completion of the first HTTP request

I have a requirement to make two http requests sequentially. The values retrieved from the first call will be used in the second call. Additionally, I need to update my component once the first http request is completed and also update it once the second ...

Understanding the fundamentals of TypeScript annotation and node package management

As a newcomer to Typescript, I have grasped the basics but find myself becoming a bit bewildered when it comes to best practices for handling node packages, annotations, and defining types within those packages in my projects. Do I really need to annotate ...