7

I have an API response that looks like this:

{
  "2019-02-13": {
    "costs": 117,
    "commission": 271.07
  },
  "2019-02-14": {
    "costs": 123,
    "commission": 160.37
  },
  //etc..
}

I want to use this object as a datasource for my material data table, but I get this error:

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

I tried using a cell definition like this:

//cost
<td mat-cell *matCellDef="let item | keyvalue"> {{item.value.costs}} </td>
//date
<td mat-cell *matCellDef="let item | keyvalue"> {{item.key}} </td>

But that didn't work.

I could of course loop through my object and make an array like this:

[
  {
    commission: 100,
    costs: 45
    date: '2019-02-13'
  },
  {
    commission: 100,
    costs: 45
    date: '2019-02-13'
  }
]

This will probably fix my problem, but I'd rather not do this because I feel like it's unnecessary.

Edit

I fixed it with adding this code to my service call:

let data = [];
for (let key in response) {
  let value = response[key];
  let obj = {date: key, commission: value.commission, costs: value.costs}
  data.push(obj);
}
return data;
Stijn
  • 171
  • 1
  • 5
  • 2
    In my opinion, do what you just said at the end and that is a very good programming practice. And if your data is coming from an API then it is going to be much easier to turn them into objects during your service call. – Thriller Feb 21 '19 at 14:01
  • If you fixed your problem, you can add it below as an "Answer" and accept it. – ryanwebjackson Feb 22 '19 at 15:38
  • I did fixed my problem, but I'm still looking for a better fix tbh. – Stijn Feb 22 '19 at 15:46

1 Answers1

1

If you would have two interfaces:

interface Foo {
  [key:string]: myDataContent[];
}
interface myDataContent{
  costs: number;
  commission: number;
}

and a service call which returns you Foo[] into a list, e.g. lstValues and the rest should be easy. The key you could get from the Object.keys

LeO
  • 4,238
  • 4
  • 48
  • 88