简体   繁体   中英

Angular Material Data Table That Hits API endpoint

I'm trying to create a Angular Material Table that displays dynamic data coming from an API endpoint but only the Table Header populates the screen without any data in it.

And it also does not throw any error...

Whenever I put hardcoded data, it works. But that's not what I want.

Here it is my table-component.ts file

import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service'
import { MatTableDataSource } from '@angular/material/table';

const COUNTRY_DATA = []

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.scss']
})

export class TableComponent implements OnInit {

  countryJSON;
  displayedColumns: string[] = ['name', 'cases', 'deaths', 'recov', 'permill'];
  dataSource = new MatTableDataSource(COUNTRY_DATA);

  constructor(private apiService: ApiService) {
  }

  ngOnInit(): void {
    this.apiService.getNews().subscribe((dataJSON) => {
      this.countryJSON = dataJSON
      for (let countryObject of this.countryJSON) {
        COUNTRY_DATA.push
          ({
            name: countryObject.country_name,
            cases: countryObject.total_cases,
            deaths: countryObject.total_deaths,
            recov: countryObject.total_recov,
            permill: countryObject.case_per_mill
          })
      }

      console.log(COUNTRY_DATA)
    })
  }
}

As you can see, I'm printing to the console what does COUNTRY_DATA has in it, and I get the expected data: An array of objects

在此处输入图片说明

But they don't populate the Table... And it looks like this:

在此处输入图片说明

Well, the main problem with your code is that you don't push your array in the datasource, instead, you're instantiating an empty instance.

if you called dataSource = new MatTableDataSource(COUNTRY_DATA); at the position of console.log(COUNTRY_DATA) it should work.

A better approach when receiving an observable response is to use map instead of a loop, here is an answer for mapping How to map a response from http.get to a new instance of a typed object in Angular 2

PS It will much better if you used an interface to introduce your object, and mapped the result in your ApiService and just set it as the value of your datasource in the component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM