2

I am trying to show data in angular material table, here is get request to fetch data from API

export class ProductsListComponent implements OnInit {
            // Table fields
            displayedColumns = ['select', 'country', 'actions'];
            datasource = ????? //how should I give api's data source 
        }

        ngOnInit() {
                    let observ = this.http.get('https://kbzp6jhg2h.execute-api.us-east-1.amazonaws.com/Prod/api/v1/hierarchy/countries?status=1');
                    observ.subscribe((res)=> {
                        console.log("response from api",res['data']);
                });

Here is html file where I want to show data coming from API

<mat-table class="lmat-elevation-z8" #table [dataSource]="dataSource">
    <ng-container matColumnDef="country">
        <mat-header-cell *matHeaderCellDef>Country Name</mat-header-cell>
        <mat-cell *matCellDef="let product">{{product.name}}</mat-cell>
    </ng-container>
</mat-table>
Junaid
  • 31
  • 5
  • 1
    No shortage of examples on the [docs site](https://material.angular.io/components/table/examples). Code: https://stackblitz.com/angular/dnbygeojrjom?file=app%2Ftable-http-example.ts – R. Richards Aug 19 '19 at 16:37
  • Well, its not showing bc you aren't setting the data from your subscription into your model. You forgot to save the data to actually show it. – Rich Aug 19 '19 at 16:44

1 Answers1

0

What about initializing datasource with an empty array and reset it when data comes from the observable ? something like :

export class ProductsListComponent implements OnInit {
            // Table fields
            displayedColumns = ['select', 'country', 'actions'];
            datasource = []

        ngOnInit() {
                    this.http.get('https://kbzp6jhg2h.execute-api.us-east-1.amazonaws.com/Prod/api/v1/hierarchy/countries?status=1')
                   .subscribe((res)=> {
                        this.datasource = res
                   });
        }

}
bubbles
  • 2,597
  • 1
  • 15
  • 40