Display Nested Data in Angular Material Table: A Step-by-Step Guide

I recently received a REST API response from the following URL:

{
  "list": [
    {
      "id": 1,
      "login": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c08190f08234d3c0508521f1311">[email protected]</a>",
      "first_name": "AK",
      "phone": "967777777777"
    },
    {
      "id": 2,
      "login": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e094859394bfd2a09994ce838f8d">[email protected]</a>",
      "first_name": "QR",
      "phone": "967777777777"
    },
    {
      "id": 3,
      "login": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd89988e89a2cebd8489d39e9290">[email protected]</a>",
      "first_name": "JM",
      "phone": "967777777777"
    }
  ],
  "count": 3,
  "success": true
}

Subsequently, I designed and implemented 2 interfaces to handle this API response:

import { List } from "./list"

export interface Users {
    list: List[]
    count: number
    success: boolean
}
export interface List {
    id: number
    first_name: string
    login: string
    phone: string
}

In addition, a custom service was created to retrieve data from the API URL:

getUsers(): Observable<Users[]>{
    //myHeader = myHeader.set('id', '123456');
    return this.http.get<Users[]>(`https://api.users.com/user/list`).pipe(
      tap(users => console.log(users)),
    );
}

Furthermore, I invoked this service within my component.ts file in the following manner:

export class UsersComponent implements OnInit{
  displayedColumns: string[] = ['id', 'first_name', 'login', 'phone'];
  users: any[] = [];

  constructor(private usersService: UsersService){ }

  ngOnInit(): void {
    this.onGetUsers();
  }

  onGetUsers(): void{
    this.usersService.getUsers().subscribe(
      (response => {
        this.users = new MatTableDataSource<Users>(response);
      })
    );
  }
}

The retrieved data is then presented in a material table as shown below:

<table mat-table [dataSource]="users" class="mat-elevation-z8">

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

    <ng-container matColumnDef="first_name">
      <th mat-header-cell *matHeaderCellDef> first_name </th>
      <td mat-cell *matCellDef="let element"> {{element.first_name}} </td>
    </ng-container>
  
    <ng-container matColumnDef="login">
      <th mat-header-cell *matHeaderCellDef> login </th>
      <td mat-cell *matCellDef="let element"> {{element.login}} </td>
    </ng-container>
  
    <ng-container matColumnDef="phone">
      <th mat-header-cell *matHeaderCellDef> phone </th>
      <td mat-cell *matCellDef="let element"> {{element.phone}} </td>
    </ng-container>
  
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

Unfortunately, no data appears in the table. How can I troubleshoot and resolve this issue?

Answer №1

Your JSON response represents a single Users object rather than an array of Users.

  1. Update the getUsers method in the service to return an Observable of type Observable<Users>.
getUsers(): Observable<Users> {
  //myHeader = myHeader.set('id', '123456');
  return this.http
    .get<Users>(`https://yapi.yementrack.com.ye/panel/user/list`)
    .pipe(tap((users) => console.log(users)));
}
  1. Change the type of the users variable to MatTableDataSource<List>. (It's suggested to rename the variable as

    userDatSource</code, but it's optional)</p>
    </li>
    <li><p>Assign the value of <code>response.list
    to the users data source.

users!: MatTableDataSource<List>;

onGetUsers(): void {
  this.usersService.getUsers().subscribe((response) => {
    this.users = new MatTableDataSource<List>(response.list);
  });
}

Check out the Demo on StackBlitz

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

Retrieve an array of specific column values from an array of objects using Typescript

How can I extract an array from an array of objects? Data var result1 = [ {id:1, name:'Sandra', type:'user', username:'sandra'}, {id:2, name:'John', type:'admin', username:'johnny2'}, ...

Using the attribute selector in an Angular 2 standalone component

In my research, I have come across several sources mentioning that an angular component selector can be enclosed in square brackets similar to a directive selector. However, when I tried it, it did not work for me: import { ChangeDetectionStrategy, Compone ...

Encountered an issue while attempting to convert a vue-cli project to TypeScript

I am currently attempting to migrate my vue-cli project to typescript. According to this resource, all I need to do is execute the following command: vue add typescript My project is being run on a Windows machine using Git Bash However, when I try to ru ...

When the parent component is linked to the child, the screen remains empty

Attempting to pass a variable from the parent component to the child component led me to utilize the @Input() method. However, when I tried to establish the connection between the two components, the entire website displayed a blank page and became unrespo ...

Refreshing issue: Model change in child page not updating view correctly (Ionic & Angular)

I am currently working with Ionic 3.20 and Angular 5.2.9, encountering an issue with content refreshing after a model change. Despite being new to this, I sense that I might be overlooking something fundamental. Within my view, I have the following elemen ...

Child component in Angular 17 failing to pass null params to app root

I'm utilizing Angular 17 with SSR. When routing to: en/home/1, I try injecting ActivatedRoute. However, I am unable to retrieve the params from the child component or the app root component. How can I get the params from the child component (app-menu ...

What is the best way to send my Array containing Objects to the reducer using dispatch in redux?

I'm currently facing an issue where I can only pass one array item at a time through my dispatch, but I need to pass the entire array of objects. Despite having everything set up with a single array item and being able to map and display the data in t ...

What is the process for exporting all sub-module types into a custom namespace?

When we import all types from a module using a custom-namespace, it appears to work smoothly, for example: import * as MyCustomNamespace from './my-sub-module' We are also able to export all types from a module without creating a new namespace, ...

How can you generate a "Package Contains Lower Node Version" error message during the installation of an NPM package if the node version is higher than the current system's node version?

I am looking for a way to trigger an error during the installation of an NPM package if the node version supported by that module does not match the system/server node version. Specifically, I want to prevent the installation of any npm module that suppor ...

Guide on populating text boxes in a form automatically using ngFor?

As a beginner Angular developer, I am looking to automatically fill in text boxes in a form, specifically 10 text boxes (10 rows) using the ngFor directive. In my research on ngFor examples, I have noticed that most of them focus on populating a list base ...

Namespace remains ambiguous following compilation

I'm currently developing a game engine in TypeScript, but I encountered an issue when compiling it to JavaScript. Surprisingly, the compilation process itself did not throw any errors. The problem arises in my main entry file (main.ts) with these ini ...

Color changes on mat-calendar when hovering

Is it possible to change the hover color of the Mat-calender element? I managed to do so using this CSS code: .mat-calendar-body-cell-content:hover { background-color:#something } The issue is that when hovering the cursor in the corner of the cell, the ...

The parameters 'event' and 'event' are not compatible with each other

I'm currently working on a page that involves submitting a form: import React from 'react'; import Form from 'react-bootstrap/Form'; import { useSignIn } from '../../hooks/Auth/useSignIn'; import { useHistory } from &apos ...

Guide on setting up component from service to display toast notifications

I am looking to implement a global toast service in my application with custom styles and HTML for the toasts. Currently, I am using ng2-toastr. For example, let's say I have a component A which contains a button in its view: <button (click)="show ...

Multiple consecutive XHR requests failed without any error message. The cause remains unknown

Here is the content of my package.json file: canActivate in my code:</p> imports: [ BrowserModule, FormsModule, ReactiveFormsModule, RouterModule.forRoot([ {//route configs path: '', redirectTo: '/cfbsetup', pathMatch: &a ...

Turning HTML into PDF using Angular 10

I am having success generating a PDF from my HTML page when the data is bound to td directly from ts. However, I face issues when trying to bind the value to an input. You can see a working example on Stackblitz. Generating a PDF for my ...

Encountering an issue with Angular where downloading a zip archive using the HttpClient API results in

Within our Angular5 web application, we are utilizing an API to retrieve a zip archive (Back-end is ASP.NET Core 2.1 using SharpZipLib). Previously, everything functioned correctly when using the old HTTP API provided by Angular :) However, after upgradin ...

Angular 2 - mastering the art of handling errors

In my Angular 2 application, I have multiple pages that call backend services. My question is how to create a universal error popup component that can display an error message whenever needed across all pages. Can anyone assist me in finding a solution f ...

Is it possible to import a class from a different project or module in TypeScript?

I am attempting to modify the build task in Typescript within this specific project: https://github.com/Microsoft/app-store-vsts-extension/blob/master/Tasks/app-store-promote/app-store-promote.ts I am looking to incorporate an import similar to the one be ...

Enhance the functionality of angular-material buttons by incorporating dynamic loading animations into

I am currently working on a solution in Angular 12 to disable a button (and show a spinner) when it is clicked, until the API responds. To achieve this, I plan to follow a similar approach to the angular-material button implementation. Essentially, I want ...