Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 830
Stijn Avatar asked Feb 21 '19 13:02

Stijn


People also ask

What is * MatCellDef in angular?

MatCellDef extends CdkCellDef Cell definition for the mat-table. Captures the template of a column's data row cell as well as cell-specific properties.

What is DataSource in angular material?

A DataSource is simply a class that has at a minimum the following methods: connect and disconnect . The connect method will be called by the table to provide an Observable that emits the data array that should be rendered.

What is filterPredicate in angular?

Default filterPredicate function combines all columns values and checks if the filter string exists in the combined string. For example consider a row in our table ab,cd. The combined string is ab◬cd. filterPredicate uses a special character(◬) in between the column values while appending.


1 Answers

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

like image 67
LeO Avatar answered Oct 11 '22 19:10

LeO