``Looking for solutions to Angular Material's mat-table not displaying data fetched from a REST API

I've been struggling to incorporate this Angular Material table example into my project.

I can see the data from my REST endpoint in the console output, so I'm not sure what I'm doing wrong.

I suspect that maybe the data isn't fully loaded when the table is rendered. Any guidance would be greatly appreciated, thank you!

lap.component.ts

import {Component, OnInit, ViewChild} from '@angular/core';
import {MatPaginator, MatSort, MatTableDataSource} from '@angular/material';
import {Router} from '@angular/router';
import {LapService} from '../shared/services/lap.service';
import {Lap} from '../shared/model/lap.model';

@Component({
  selector: 'app-lap',
  templateUrl: './lap.component.html',
  styleUrls: ['./lap.component.css']
})
export class LapComponent implements OnInit {

  displayedColumns = ['id', 'year', 'lap', 'shortcut flag', 'start place', 'destination place', 'length', 'height difference'];
  dataSource: MatTableDataSource<Lap>;

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;


  constructor(public rest: LapService, private router: Router) {
  }

  ngOnInit() {
    this.dataSource = new MatTableDataSource(this.getLaps());
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }


  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  getLaps() {
    this.rest.getLaps().subscribe((data: {}) => {
      console.log(data);
      console.log('Laps');
      return data;
    });
  }
}

lap.component.html

...

Answer №1

To start, remember to initialize a new instance of MatTableDataSource() and then when data is received, assign it to the dataSource.data array.

 ngOnInit() {
   // this.dataSource = new MatTableDataSource(this.getLaps());
    this.dataSource = new MatTableDataSource(); // create new object
    this.getLaps(); // don't forget this line
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
 }

   getLaps() {
     this.rest.getLaps().subscribe((data: {}) => {
       console.log(data);
       console.log('Laps');
       this.dataSource.data = data; // populate dataSource.data array with received data
       return data;
    });
  }

Answer №2

Don't forget to include the following line in your ngOnInit method:

this.retrieveData(); 

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

Scroll event not triggering in Angular Material

I've encountered an issue while creating an angular app using angular material that involves a scroll event. The setup of my app includes a fixed left sidenav and content on the right. Despite trying to inspect the scroll on the right content, I have ...

React useContext with TypeScript error: "property is not recognized on '{}'"

I have organized a context to distribute Firebase authentication objects in the following way: export function AuthProvider(props: {children: React.ReactNode}) { const [user, setUser] = useState<IUser>({uid: ""}); useEffect(() => ...

Issue with Angular: Attempting to assign a value to a property that is undefined within

While utilizing a common method to call a service that executes two functions upon success and failure, I encountered an issue. Despite the call executing correctly, I faced an error when trying to assign a value from the service result to a variable withi ...

What is the process for creating an additional username in the database?

As a beginner frontend trainee, I have been tasked with configuring my project on node-typescript-koa-rest. Despite my best efforts, I encountered an error. To set up the project, I added objection.js and knex.js to the existing repository and installed P ...

Customizing Material UI CSS in Angular: A Guide

Recently, while working with the Mat-grid-tile tag, I noticed that it utilizes a css class called .mat-grid-tile-content, which you can see below. The issue I am encountering is that the content within the mat-grid-tile tag appears centered, rather than f ...

Implementing a feature in Angular 7 to retrieve data from local storage and set it as the default redirect route

import { NgModule, OnInit } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AuthGuardService } from './../providers'; import { AdminComponent } from './../admin/admin.com ...

What is the process for bringing my API function into a different Typescript file?

I've successfully created a function that fetches data from my API. However, when I attempt to import this function into another file, it doesn't seem to work. It's likely related to TypeScript types, but I'm struggling to find a soluti ...

Verify if TypeScript object contains a specific key dynamically without the need for a custom type guard

Using TypeScript's in keyword allows us to check if an object contains a specific key in a type-safe manner when the key is defined as a string literal: function guardHasTest <Data extends object> ( value: Data ): Data & Record<'te ...

Issue with updating @input within ngFor loop's binding circuit

I am dealing with a component that has two binded inputs, which are a large array and two markers indicating positions within the array. This is how the component looks: export class listSequence { @Input() info: Data; @Input() position: Markers; .. .. ...

Define the base URL for the Angular ClientApp hosted by the ASP.NET Core WebApi

After setting up an ASP.NET Core project that serves an Angular app using various methods like services.AddSpaStaticFiles(), app.UseSpaStaticFiles(), and app.UseSpa(), I encountered a challenge. The issue is that the application is currently being served ...

Tips for deploying an Angular 6 project and a Spring Boot project together as a unified deployment package

I have two separate projects - one is an Angular Project (Front End Application) and the other is a Spring Boot (Rest Api's) project. When I run each project individually, everything works fine. Now, I want to create a single runnable jar file that co ...

What is the process for incorporating the error type of useQueries in a TypeScript project?

Currently, I am utilizing react-query's useQueries function to create a unique custom hook named useArtists: type SuccessResponse = { artist: { name: string } }; const fetchArtist = async (artistId: string): Promise<SuccessResponse> =& ...

The addition operator is not compatible with the given types

Hello, I am currently working on integrating PayPal into an Angular 5 project. The code snippet below shows how I render PayPal buttons using a function: ngAfterViewChecked(): void { if (!this.addScript) { this.addPaypalScript().then(() => { ...

Tips for parsing text responses in React to generate hyperlinks and emphasize specific words

I'm currently tackling a React project and facing an interesting challenge. I have a text response that needs to be parsed in a way that all URLs are automatically turned into clickable hyperlinks (using anchor tags). Moreover, there's a requirem ...

Using Express and Node.js, fetch an image from one localhost and transfer it to another localhost

I am currently developing a NodeJs and Angular app The server is running on http://localhost:9000 While the app itself runs on http://localhost:4200 One of my endpoints looks like this http://localhost:9000/users, which I use to fetch all user data The ...

Error encountered: EPERM

I am currently using node v6.11.2, npm v5.3.0 and angular/cli v1.2.7. Recently, I've started encountering a new error message during most of my npm installs that I have never seen before... mmeppiel@MC-LT-MMEPPIEL MINGW64 ~/Desktop/Angular Solutions ...

typescript code: transforming object values into keys in typescript

Here is a scenario: const obj1 = { a: 'x', b: 'y', c: 'z', } I am looking to automatically create a type like this: type Type = { x: number, y: number, z: number, } I initially considered the following approach: ...

It appears that the input variables in Angular (5) are experiencing some issues

After upgrading my Angular project from version 4 to 5, I've noticed some unexpected changes in the behavior of my components. In my application, there is a ParentComponent and a ChildComponent. The ChildComponent receives an InputObject from its par ...

How to utilize Array.reduce in Node Streams with Typescript

I am still getting the hang of using typescript and am just starting to explore more advanced type declarations. Currently, I am experimenting with chaining a series of node.js stream transforms onto an incoming node.js stream using the reduce method. Th ...

Troubleshooting ngFor usage with Object Arrays in Angular 2

I have created an Array of Objects in my Component class as shown below : deskCategories : Array<any>; this.deskCategories = [ { catLabel : 'Tools', catIcon : 'suitcase' }, { ...