What am I missing? I verified that my API is returning data back however I can't get the data to display in my table.
Verified data:
<pre>{{ myData| json }}</pre>
Html
<div *ngIf="dataSource">
<mat-table [dataSource]='dataSource'>
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
<mat-cell *matCellDef="let df"> {{df.name}} </mat-cell>
</ng-container>
<ng-container matColumnDef="path">
<mat-header-cell *matHeaderCellDef> Path </mat-header-cell>
<mat-cell *matCellDef="let df"> {{df.path}} </mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="columnsToDisplay"></mat-header-row>
<mat-row *matRowDef="let df; columns: columnsToDisplay"></mat-row>
</mat-table>
</div>
Typescript:
export class HomeComponent implements OnInit {
columnsToDisplay = ['name', 'path'];
myData: IMyData[];
dataSource = new MatTableDataSource<IMyData>(this.myData);
constructor(private myDataService: MyDataService) {
console.log("IN CONSTRUCTOR");
}
ngOnInit(): void {
this.myDataService.getData()
.subscribe(x => this.myData = x,
error => console.log("Error (GetData) :: " + error)
); }
}
EDIT: I wonder if it has to do with my interface:
Interface
export interface IMyData {
id: string;
path: string;
date: Date;
location: Geolocation;
name: string;
gizmos: string[];
}
Example Data:
[
{
"id": "9653a6b5-46d2-4941-8064-128c970c60b3",
"path": "TestPath",
"date": "2018-04-04T08:12:27.8366667",
"location": "{\"type\":\"Point\",\"coordinates\":[102.0,0.5]}",
"name": "TestName",
"gizmos": [
"AAAA",
"BBBB",
"CCCC"
]
}
]
First mistake is the incorrect data binding with single quotes instead of double quotes:
Change
<mat-table [dataSource]='dataSource'>
To this:
<mat-table [dataSource]="dataSource">
Second mistake is incorrect data source initialization. You should create the
MatTableDataSource
after fetching the data from the service.You need to update the datasource, not just the variable containing the data
and set correct binding
in my case, I inherited from
MatTableDataSource
to createMyDataSource
. Without calling afterthis.data = someArray
data where not displayed
class MyDataSource