У меня есть проект, который использует массив данных, но я хочу иметь возможность доступа к внешним данным, таким как файл JSON или API, с помощью него вместо жесткого кодирования их в проект. Я добавил запрос http get для извлечения файла JSON, но если я изменю Observable с this.arrayData
на this.jsonData
, ничего не появится. Кто-нибудь сможет мне помочь?
app.component.ts
ngOnInit() {
Rx.Observable.from(this.arrayData[0].data)
.groupBy(x => x.customer.name) // using groupBy from Rxjs
.flatMap(group => group.toArray()) // GroupBy doesn't create an array object so you have to flat it
.map(g => {
// mapping
return {
name: g[0].customer.name, //take the first name because we grouped them by name
price: _.sumBy(g, "billing_stage_net_value") // using lodash to sum price
};
})
.toArray() //.toArray so that you can loop on it with ngFor
.do(sum => console.log("sum:", sum)) // just for debug
.subscribe(d => (this.groupedArrayData = d));
// pull from Json
this.jsonData = this.http
.get("assets/transactions.json")
.map(data => _.values(data))
.do(console.log);
}
app.component. html
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody *ngFor="let data of groupedArrayData">
<tr>
<td>{{data.name}}</td>
<td>€{{data.price}}</td>
</tr>
</tbody>
</table>
транзакций. json (те же данные, что и в массиве)
{
"data": [
{
"billing_stage_net_value": 15.160000000000,
"customer": {
"name": "Harbour Cafe"
},
"id": 1142,
"transaction_date": "2019-10-22T13:56:11.971643+00:00"
},
{
"billing_stage_net_value": 51.000000000000,
"customer": {
"name": "Crisp Sandwich Cafe"
},
"id": 1143,
"transaction_date": "2019-10-22T13:57:24.375087+00:00"
},
{
"billing_stage_net_value": 13.500000000000,
"customer": {
"name": "Crisp Sandwich Cafe"
},
"id": 1144,
"transaction_date": "2019-10-22T13:57:24.375087+00:00"
}
],
"message": "",
"metadata": {},
"success": true
}