简体   繁体   中英

How to use key-value object as datasource for Angular Material table

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;

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, eg lstValues and the rest should be easy. The key you could get from the Object.keys

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM