Ad

How To Properly Format This Data For Material Table [dataSource]?

- 1 answer

I can get the data from the API to show using *ngFor='let earning of symbolEarnings.earnings'>{{earning.actualEPS}}Now I'm trying to use the mat-table so it's uniform with the rest of my app.

Now if I use symbolEarnings which is an object Object in the [dataSource], I get the error

Provided data source did not match an array, Observable, or DataSource

Now what I've been doing for the past hours is trying to convert to an array. As reference, this is the data.

{"symbol":"AAPL","earnings":
[
{"actualEPS":2.91, "EPSReportDate":"2018-11-01"},
{"actualEPS":2.34,"EPSReportDate":"2018-07-31"}
]}

So I use this to get symbolEarnings

    getEarning(): void {
        const id = this.route.snapshot.paramMap.get("id");
        this.svc.getEarningById(id).subscribe(data => {
          this.symbolEarnings = data;

which works fine when I do 'let x of symbolEarnings.earnings' {{x.actualEPS]]

The data is currently an object Object, so I get the error highlighted above.

I try to convert the earnings part into an array to no avail. this.test = this.symbolEarnings.earnings; or this.testArray = Object.keys(this.test).map(i => this.test[i]);

The interesting thing is that testArray works for [dataSource] but I need to do *ngFor='let y of testArray' [dataSource]="testArray" to get the column then use <td mat-cell>{{y.actualEPS}}</td> which produces result but it's repeating on multiple table.

For example, EPS: 2, 2, 2 EPS: 3, 3, 3 EPS: 4, 4, 4 rather than EPS: 2, 3, 4

So I kinda sorta got it kinda working, but I clearly need some help with this. Let me know if you have any questions! Thank you

Ad

Answer

I got it to work. Turns out it was *matCellDef="let element">{{element.actualEPS}}, where that's only referencing MatTableDataSource. So I used dataSource = new MatTableDataSource(); then

  getEarning(): void {
    const id = this.route.snapshot.paramMap.get("id");
    this.svc.getEarningById(id).subscribe(data => {
      this.symbolEarnings = data;
      this.symbolEarningsDetail = this.symbolEarnings.earnings;
      this.dataSource.data = this.symbolEarningsDetail;

Ad
source: stackoverflow.com
Ad