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

How can I activate caching with Prerender.io?

After successfully setting up prerender on my local machine, everything is working smoothly with all pages properly prerendered. However, the process always takes 5-10 seconds. Does anyone have a recommendation for implementing caching on a local Prerend ...

Tips for invoking a function from one React component to another component

Currently, I am working on two components: one is Game and the other is PickWinner. The Game component serves as the parent component, from which I need to call the pickWinner function in the PickWinner component. Specifically, I want to trigger the startP ...

Tips for resolving conflicts between sequelize and angular within a lerna monorepo using typescript

Managing a monorepo with Lerna can be quite challenging, especially when working with both Node.js and Angular in the same project. In my setup, Angular is using "typescript": "~3.5.3". For Node.js to work seamlessly with Sequelize, I have the following ...

Issue with data not refreshing when using router push in NextJS version 13

I have implemented a delete user button on my user page (route: /users/[username]) which triggers the delete user API's route. After making this call, I use router.push('/users') to navigate back to the users list page. However, I notice tha ...

Unpacking intricate function arguments in TypeScript

I am working with the following model classes: export class Book { public name: string; public id: string; ... } export class Author { public firstName: string; public lastName: string; ... } The my-component triggers an event t ...

Transfer the data stored in the ts variable to a JavaScript file

Is it possible to utilize the content of a ts variable in a js file? I find myself at a loss realizing I am unsure of how to achieve this. Please provide any simple implementation suggestions if available. In my ts file, there is a printedOption that I w ...

`As the input value for these methods`

I am encountering an issue when trying to pass in this.value as a method argument. The field values are all strings and the constructor arguments are also all strings, so I don't understand why it's not working. When I attempt to pass in this.cla ...

Error in Typescript: A computed property name must be one of the types 'string', 'number', 'symbol', or 'any'

Here is the current code I am working with: interface sizes { [key: string]: Partial<CSSStyleDeclaration>[]; } export const useStyleBlocks = ( resolution = 'large', blocks = [{}] ): Partial<CSSStyleDeclaration>[] => { cons ...

Revamping every Angular component

Looking for a shortcut to upgrade all my Angular components at once. When checking my Angular version with ng v globally in VS Code terminal, results differ between overall and project directory settings: https://i.stack.imgur.com/2iOJx.png https://i.st ...

Creating void functions in TypeScript

I encountered a section of code within a custom component that is proving to be quite puzzling for me to comprehend. public onTouch: () => void = () => {} The function onTouch is being assigned by the private method registerOnTouch(fn: any) { ...

Using Typescript to inherit from several classes with constructors

I am trying to have my class extend multiple classes, but I haven't been able to find a clean solution. The examples I came across using TypeScript mixins did not include constructors. Here is what I am looking for: class Realm { private _realms: C ...

I require assistance in comprehending async/await in order to ensure that the code will pause and wait for my http.get function to

I've been reading various articles and forums, both here and on Google, about using awaits and asyncs in my code. However, no matter where I place them, the code after my http.get call always executes first. The alert messages from the calling program ...

Having trouble importing a file in TypeScript?

I needed to utilize a typescript function from another file, but I encountered an issue: I created a file called Module.ts with the following code snippet: export function CustomDirective(): ng.IDirective { var directive: ng.IDirective = <ng.IDire ...

Tips for Passing On Parent tabindex Value to Children

Is there a way to propagate a parent's tabindex value to all of its children without individually setting tabindex for each child? Here is an example code snippet: <div id="app"> <div tabindex="2" class="parent-sec ...

What is the meaning of "bootstrapping" as it relates to Angular 2?

I found a question that is similar to mine, but I think my case (with version 2) has enough differences to warrant a new discussion. I'm curious about the specific purpose of calling bootstrap() in an Angular 2 application. Can someone explain it to ...

What could be the cause of this malfunction in the Angular Service?

After creating an Angular app with a controller, I noticed that while I can successfully interact with the controller using Postman (as shown in the screenshot below), I faced issues with displaying data at the frontend. I implemented a new component alon ...

Leveraging Runtime Environment Variables in Angular 5 within the app.module.ts File

I am currently utilizing a third-party authentication module called OktaAuthModule. In order to import it into my root module (app.module.ts), I must first configure it as follows: const config = { url: https://myurl.com/ } @NgModule({ declaration ...

When merging interfaces and classes, Typescript does not verify property initialization

When creating a class like the following: class Dog { a: string; b: string; c: string; } The TypeScript compiler will throw an error stating that properties a, b, and c are not initialized. However, if we take a different approach like this: i ...

Add a class individually for each element when the mouse enters the event

How can I apply the (.fill) class to each child element when hovering over them individually? I tried writing this code in TypeScript and added a mouseenter event, but upon opening the file, the .fill class is already applied to all elements. Why is this ...

Updating Facebook meta tags dynamically in Angular 4 to enhance Open Graph integration

Is there a way to dynamically update meta tags for Facebook/Whatsapp share dialog? I recently upgraded my angular 2 application to angular 4 in order to utilize the Meta service and update meta tags dynamically once data is retrieved from an API. Within ...