How can i put this object in material table in angular

Viewed 379

Currently i am working on a project where I am required to gather data from an aws aurora database and display it on a table. I am planning on using a material table and I cannot figure out how to place the data in the table.

Here is the component that gathers asks for the data:

import { Component, OnInit } from '@angular/core';
import { CandidateService} from '../../shared/candidate.service';
import { MatTableDataSource, MatTableModule} from '@angular/material/table';

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

  candidateRecordAvailabe: boolean = false;
  tableData: MatTableDataSource<any>;
  displayColumns: string[] = ['first_name'];
  constructor(private candidateService: CandidateService) { }

  //Variables for the component


  ngOnInit() {
    this.fetchCandidateRecords();
    this.putCandidateRecords();
  }  

  /* fetch candidates from the candidates service and retrying till aws aurora server starts */
   async fetchCandidateRecords(){
    //check if candidate list already exists in the candidate.service
    if(this.candidateService.candidateRecords == null) {
      await this.candidateService.fetchAllCandidates().subscribe(
        (recordData: []) => {  
          console.log(typeof(recordData));
          console.log(recordData);
          this.candidateService.candidateRecords = recordData;
          this.candidateRecordAvailabe = true;
          this.tableData = new MatTableDataSource(this.candidateService.candidateRecords);
        }, 
        (error) => {
          console.error(error);
        }
      );
    }
    else {
      this.candidateRecordAvailabe = true;
      this.tableData = new MatTableDataSource(this.candidateService.candidateRecords);
    }
  }

  putCandidateRecords(){
    this.tableData = new MatTableDataSource(this.candidateService.candidateRecords);
  }

}

Below is the service function that subscribes to the HTTP request and collects the data

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders, HttpErrorResponse} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { retryAfterDelay } from './custom.delay';


@Injectable({
  providedIn: 'root'
})
export class CandidateService {
  constructor(private http:HttpClient) { }

  candidateRecords: [] = null;   // Stores the records of all the candidates from fetch candidates
  delayDuration: number = 20000;  //20 seconds of delay

  fetchAllCandidates(): Observable<Object>{
    return this.http.get('url--here---')
      .pipe(
       retryAfterDelay(this.delayDuration),
       catchError(errorResponse => {
         return throwError(errorResponse);
       }
      )
      );
  } 

}

Here is my HTML code:

<div class="mat-elevation-z0" *ngIf="candidateRecordAvailabe">
    <mat-table [dataSource]="tableData">
        <mat-header-cell>first_name</mat-header-cell>   
        <ng-container matColumnDef="first_name">
            <mat-header-row *matHeaderRowDef="displayColumns"></mat-header-row>
            <mat-cell *matCellDef="let element">{{ element.first_name|json}}</mat-cell>
        </ng-container>
        <mat-row *matRowDef="let row; columns: displayColumns;"></mat-row>
    </mat-table>
</div>

<div class="container h-100" *ngIf="!candidateRecordAvailabe">
    <div class="row align-items-center h-100">
        <div class="col-6 mx-auto uploader-status ">
                <mat-spinner strokeWidth="25" [diameter]="100" title="Server Starting" ></mat-spinner>
        </div>
    </div>
</div>

Now, here is the error I am facing. The below images also consist of the type of data I am receiving

enter image description here

enter image description here

1 Answers

There is a slight mistake in your code as per documentation in your html the ng-container part will be like this as follows:

<ng-container matColumnDef="{{column}}" *ngFor="let column of displayColumns; index as i">
  <th mat-header-cell *matHeaderCellDef>
    {{ column=='first_name' ? 'First Name' : '' }}
  </th>
  <td mat-cell *matCellDef="let element">{{ element.first_name | json }}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayColumns"></tr>

The problem with your part was you were not iterating the displayColumns to extract each column and put in matColumnDef.

I hope this documentation in Angular material will help you.

Related