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;
3
  • 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. Commented Feb 21, 2019 at 14:01
  • If you fixed your problem, you can add it below as an "Answer" and accept it. Commented Feb 22, 2019 at 15:38
  • I did fixed my problem, but I'm still looking for a better fix tbh. Commented Feb 22, 2019 at 15:46

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.