1

I am working on the task to fetch data using REST API in angular 8.0.0, while doing so i am getting errors as below:

enter image description here

My task was to display data into the Mat Table on page.

item.ts

import { Execution } from './execution';
export class Items {
    items: Exec[];
}

execution.ts

export class Exec {
    test: number;
    test1: string;
}

execution.component.ts

export class ExecutionComponent implements OnInit {
  runData: Items;
  constructor(private executionService: ExecutionService) { }  
  displayedColumns: string[] = ['test', 'test1'];  
  //@ViewChild(MatSort, { static: true }) sort: MatSort;

  dataSource = new MatTableDataSource<Execution>(this.runData.items); //error showing at this point
  ngOnInit() { 
    this.executionService.getArtifactDetails().subscribe(
      (response:Items) => {
        this.runData = response;
        console.log(this.runData);
      }
    );  
  }
}

Sample JSON

{
    "items": [
        {
            "test": 1,
            "test1": "ABC"
        },
        {
            "test": 2,
            "test1": "EFG",
    ]
}
R. Richards
  • 24,603
  • 10
  • 64
  • 64
pulse
  • 169
  • 1
  • 17

1 Answers1

2

this.runData is assigned value asynchronously. So it must be used after the value is assigned, inside the subscription. Try the following

dataSource: MatTableDataSource<Execution>;

ngOnInit() { 
  this.executionService.getArtifactDetails().subscribe(
    (response: Items) => {
      this.runData = response;
      console.log(this.runData);
      this.dataSource = new MatTableDataSource<Execution>(this.runData.items);
    }
  );  
}

More info no how to access asynchronous data: https://stackoverflow.com/a/14220323/6513921

ruth
  • 29,535
  • 4
  • 30
  • 57