vaibhav naik
vaibhav naik

Reputation: 169

How to include json data in angular material data table?

I used the code given in this site to create a datatable. the url is:https://stackblitz.com/angular/dnbermjydavk?file=app%2Ftable-overview-example.html

in this code the data to be displayed in the table is hardcoded, but i wanted to display a json data which is fetched from a api.

I had already created a service component for fetching the data from api, but i am feeling difficulty in implementing this json data inside datatable.

How to use it inside the data table to display all the json data.

    my service component 
  </
    bloghttpservice.ts


    import { Injectable } from '@angular/core';

    import { HttpClient, HttpHeaders, HttpClientModule } from 
    '@angular/common/http';

    import { HttpErrorResponse, HttpParams } from '@angular/common/http';

    import { Observable } from 'rxjs/Observable'
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/operator/do';

    @Injectable({
     providedIn: 'root'
     })

    export class BankhttpService {

    private baseUrl = "https://vast-shore-74260.herokuapp.com/banks";
    public myCity = "MUMBAI"

    constructor(private _http : HttpClient) {
    console.log('Bank http service called');
   }

   private handleError(err:HttpErrorResponse){
   console.log('Handle http error');
   console.log(err.message);
   return Observable.throw(err.message);
   }


   public getBankBranches(): any {
   let myResponse = this._http.get(this.baseUrl + '?city=' + this.myCity);
   console.log(myResponse);
   return myResponse;
   }
   }

 />

Upvotes: 3

Views: 12839

Answers (1)

Ian A
Ian A

Reputation: 6128

You should be able to inject the BankHttpService and make a call to the getBankBranches() method in the constructor of your component that hosts the table. In the callback function of the Observable, you can create a new MatTableDataSource (passing in the data returned by the service) and assign it to this.dataSource so that it will be used as the table data:

constructor(private _bankHttpService: BankHttpService) {
    this._bankHttpService.getBankBranches().subscribe((branches) => {
        this.dataSource = new MatTableDataSource(branches);
    });
}

The HTML for the mat-table will need to define the correct columns, and you can display the data in the cell using row.<property_name> (e.g. row.bank_id if you want to display the bank_id JSON property):

<mat-table [dataSource]="dataSource" matSort>
    <!-- Address Column -->
    <ng-container matColumnDef="address">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Address </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.address}} </mat-cell>
    </ng-container>

    <!-- Bank ID Column -->
    <ng-container matColumnDef="bank_id">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Bank ID </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.bank_id}} </mat-cell>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.bank_name}} </mat-cell>
    </ng-container>

    <!-- City Column -->
    <ng-container matColumnDef="city">
      <mat-header-cell *matHeaderCellDef mat-sort-header> City </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.city}} </mat-cell>
    </ng-container>

    <!-- District Column -->
    <ng-container matColumnDef="district">
      <mat-header-cell *matHeaderCellDef mat-sort-header> District </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.district}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;">
    </mat-row>
</mat-table>

The displayedColumns in the table component TypeScript file will need to reflect the columns you define in the HTML:

displayedColumns = ['address', 'bank_id', 'name', 'city', 'district'];

I've created a StackBlitz demonstrating the above. It may take a few seconds to load as there are over 3000 items in your JSON response.

Upvotes: 2

Related Questions