3

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;
   }
   }

 />
2
  • what is your difficulty, you got any errors? Commented Jul 11, 2019 at 17:53
  • No , i havent got any errors .as given in this post "stackblitz.com/angular/…" the code is hardcoded to show the details in a data table but i want to show the details that i got through api in data table. how to do it. in templates interpolation is used to show those data but how to show it in data table? Commented Jul 11, 2019 at 18:12

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thank you Ian A for helping, 4 hrs code i used one of your codes from "stackblitz.com/edit/…" to implement it and now the project looks like this the same way as you have done it it in StackBlitz for me. Can you help me with another small coding problem in this project?
According to the assignment i have to mark some banks as favourites. View banks that were marked as favourites (favourites should persist state event if the website is refreshed or reloaded) . How to implement it. Can you help me out? Should array be used? and also to select the data from rows there is documentation provided in angular material. this is link material.angular.io/components/table/overview how to implement it in my code
I've created this StackBlitz to show how favourites could work. The relevant code is the new service favourite.service.ts, lines 11-16 of table-overview-example.html and lines 21-35 of table-overview-example.ts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.