How can I fetch data from a JSON API using the following code:
var options = {
chart: {
type: "bar",
},
series: [
{
name: "Bitcoin",
data: [],
},
],
xaxis: {
categories: [5, 30, 60],
},
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
I want data() to return the following amountList array, which contains numbers inside:
function data() {
return {
apiEndPoint: "https://api.coinbase.com/v2/prices/spot?currency=",
apiData: [],
amountList: [],
};
};
Related
I want to display a graph on my web interface. I want to implement the web interface with vue js. For this I pass data from my backend to my frontend with axios. I can display an empty graph on my rsurface. But the data I pass is not displayed. What is wrong with my code that my data is not displayed on the graph.
In the following you can see my implemented code.
<b-container class="ml-auto">
<b-row>
<b-col>
<vue-plotly :data="dataA" :layout="layout" :options="options"/>
</b-col>
</b-row>
</b-container>
export default {
components: {
VuePlotly,
},
data() {
return {
dataA: [{
x: [],
y: [],
}],
layout: {
title: 'ScreePlot',
bargap: 0.05,
xaxis: {
range: [0, 9],
title: 'x',
tick0: 0,
dtick: 1,
},
yaxis: {
range: [0, 2000],
title: 'y',
tick0: 0,
dtick: 1,
},
},
options: {
displayModeBar: false,
responsive: true,
watchShallow: true,
autoResize: true,
},
};
},
mounted() {
this.getScreePlot();
},
methods: {
getScreePlot() {
const path = 'http://localhost:5000/Diagramm';
axios.get(path)
.then((res) => {
this.dataA.x = res.data.x;
this.dataA.y = res.data.y;
})
.catch((error) => {
// eslint-disable-next-line
console.error(error);
});
},
},
};
In case this definition
dataA: [{
x: [],
y: [],
}],
You should fill like this:
.then((res) => {
this.dataA.push(
{
x: res.data.x,
y: res.data.y
}) ;
})
i'm looking for a solution to update an echart when new data comes in. Currently i have a chart and a drop down with some data.When i open the page, data is displaying at the chart perfectly fine. But when i use the drop down and change option to next data, nothing is happening. The previous data is still on the chart. Any ideas how to update the chart (object) when data changes ?
My code:
chart1: EChartOption = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
legend: {
data: ['Tests Open','Tests Approved', 'Tests Failed']
},
toolbox: {
show: true,
feature: {
mark: { show: true },
magicType: { title: '1', show: true, type: ['line', 'bar',] },
restore: { title: 'Restore', show: true },
saveAsImage: { title: 'Save Chart',show: true }
}
},
xAxis: [
{
type: 'category',
axisTick: { show: false },
data: []
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: 'Tests Open',
type: 'bar',
data: [],
itemStyle: {
color: '#FDD051'
}
},
{
name: 'Tests Approved',
type: 'bar',
data: [],
itemStyle: {
color: '#2EAD6D'
}
},
{
name: 'Tests Failed',
type: 'bar',
data: [],
itemStyle: {
color:'#F0533F'
}
},
]
};
refreshChart(statistics: TestResultSiteStatistics) : void {
let months = [];
let open = [];
let approved = [];
let failed = [];
for (let month in statistics.monthly){
months.push(month);
approved.push(statistics.monthly[month].approved);
open.push(statistics.monthly[month].open);
failed.push(statistics.monthly[month].failed);
}
this.chart1.xAxis[0].data = months;
this.chart1.series[0].data = open;
this.chart1.series[1].data = failed;
this.chart1.series[2].data = approved;
}
<div #chart style="height:590px; width:1190px;" echarts [options]="chart1" ></div>
You cannot add data directly to instance because Echarts incapsulated diffucult logic to process data. You need to use method myChart.setOption({series: [new_data]}). It explained in API docs: https://echarts.apache.org/en/api.html#echartsInstance.setOption and https://echarts.apache.org/en/tutorial.html#Loading%20and%20Updating%20of%20Asynchronous%20Data
Im trying to map JSON Data to show it in a Bar-Chart. The final Array I need has to look like this:[883, 5925, 17119, 27114, 2758].
Actually, the Array I want to use to set the barChartData (dringlichkeitenValues[])seems to be empty. Sorry for my bad coding skills. Can anyone show me how to solve this Problem?
JSON:
[{
"id": 1,
"value": 883
},
{
"id": 2,
"value": 5925
},
{
"id": 3,
"value": 17119
},
{
"id": 4,
"value": 27144
},
{
"id": 5,
"value": 2758
}]
api.service.ts
getDringlichkeiten(): Observable<IDringlichkeit[]> {
return this.http.get<IDringlichkeit[]>(this.ROOT_URL + '/aufenthalte/dringlichkeit');}
dringlichkeit.ts
export interface IDringlichkeit {
id: number;
value: number;
}
bar-chart.component.ts
export class BarChartComponent implements OnInit {
public dringlichkeitValues:number[] = [];
public dringlichkeiten: IDringlichkeit[];
public barChartLabels:String[] = ["1", "2", "3", "4", "5"];
public barChartData:number[] = this.dringlichkeitValues;
public barChartType:string = 'bar';
constructor(private aufenthaltService: AufenthaltService) {
}
ngOnInit() {
this.loadData();
this.getDringlichkeitValues();
}
loadData(){
this.aufenthaltService.getDringlichkeiten()
.subscribe( data => this.dringlichkeiten = data);
}
getDringlichkeitValues(){
let dringlichkeitValues:number[]=[];
this.dringlichkeiten.forEach(dringlichkeit=>{
dringlichkeitValues.push(dringlichkeit.value)
this.dringlichkeitValues = dringlichkeitValues;
});
return this.dringlichkeitValues;
}
}
UPDATE:
I updated my component but now my Array is still empty after subscribing to the Observable.
bar-chart.component.ts
chart: Chart;
dringlichkeiten: IDringlichkeit[] = [];
constructor(private aufenthaltService: AufenthaltService) {
}
ngOnInit() {
this.aufenthaltService.getDringlichkeiten()
.subscribe( data => {
this.dringlichkeiten = data;
//dringlichkeiten-Array full
console.log(this.dringlichkeiten);
});
//dringlichkeiten-Array empty
console.log(this.dringlichkeiten);
this.chart = new Chart('canvas', {
type: 'bar',
data: {
labels: this.dringlichkeiten.map(x => x.id),
datasets: [
{
label: 'Dringlichkeiten',
data: this.dringlichkeiten.map(x => x.value),
backgroundColor: ['#FF6384', '#4BC0C0', '#FFCE56', '#E7E9ED', '#36A2EB']
}
]
},
});
}
To get the "values" from your JSON array, you can use:
dringlichkeiten.map(x => x.value)
This will get you an array you require, i.e.:
[883, 5925, 17119, 27114, 2758]
You can then pass this array to chartJS for it to render you a chart like so:
this.chart = new Chart('canvas', {
type: 'bar',
data: {
labels: dringlichkeiten.map(x => x.id),
datasets: [
{
label: 'My Bar Chart',
data: dringlichkeiten.map(x => x.value),
backgroundColor: ['red', 'green', 'yellow', 'blue', 'orange']
}
]
},
});
Take a look at this simplified working SlackBlitz example.
Hope this helps!
I have 2 different JSON object
JSON1
[
{
title: "Order Rule Violations",
type: "FieldView",
panel: "expanded",
data: [
{
label: "Rule Description",
type: "text",
},
{
label: "comments",
type: "inputarea",
},
],
},
]
JSON2
[
{
data: [
{
value: "00695",
},
{
value: " ",
},
],
},
]
I need to combine and get a result like
[
{
title: "Order Rule Violations",
type: "FieldView",
panel: "expanded",
data: [
{
label: "Rule Description",
type: "text",
value: "00695",
},
{
label: "comments",
type: "inputarea",
value: " ",
},
],
},
]
Please advise how can I achieve this using Angular / Typescript
This shall for this case:
for(var i=0;i<JSON1[0].data.length;i++)
JSON1[0].data[i].value= JSON2[0].data[i].value;
I altered JSON2 a little bit like JSON2 = ["","","",....] and the code below
worked for me ,
var k=0;
for(var i=0; i<this.JSON1.length; i++){
for(var j=0; j<this.JSON1[i].data.length; j++){
console.log("j",j);
this.JSON1[i].data[j].value = this.JSON2[k];
k++;
}
}
You can use use a nested Object.assign to iterate over each array and then merge the two objects.
const json1 = [{
title: 'Order Rule Violations',
type: 'FieldView',
panel: 'expanded',
data: [{
label: 'Rule Description',
type: 'text',
},
{
label: 'comments',
type: 'inputarea',
},
],
}];
const json2 = {
data: [{
value: '00695',
},
{
value: ' ',
},
]
};
const json3 = json1.map(y => {
y.data = y.data.map(
(x, index) => Object.assign(x, json2.data[index])
);
return y;
});
console.log(json3);
Another solution is to use Lodash's _.merge function
I seem to be having an issue getting my ng-grid directive to populate from a returned REST api json obj.
I have verfied that a valid json obj is returned and i have retrieved a nested obj of the data I need. It seems that it is not making it into the gridOptions function. Where myData is the correct valid json.
Any help will be greatly appreciated. I am pulling my hair out at this point.
Here is my service:
grid-service.js
'use strict';
app.factory('GridService', ['$http', '$q', function($http, $q) {
var apiUrl = "http://xx.xx.xx.xx/coName/public/index.php/";
// configure the send request
function sendRequest(config){
var deferred = $q.defer();
config.then(function(response){
deferred.resolve(response);
}, function(error){
deferred.reject(error);
});
return deferred.promise;
}
// retrieve all
function getRoles() {
var request = $http({
method: 'GET',
url: apiUrl + 'roles'
});
return sendRequest(request);
}
return {
getRoles: getRoles
};
}]);
I inject it into my ctrl here, and my init function and gridOption functions:
app.controller('ModuleCtrl', [ '$scope', '$http', '$modal', '$filter', 'GridService', function($scope, $http, $modal, $filter, gridService) {
var initializeGrid = function(){
getRoles();
};
var getRoles = function(){
gridService.getRoles().then(function(myRoles){
var myRolesData = myRoles.data._embedded.roles;
$scope.myData = myRoles.data._embedded.roles;
console.log($scope.myData);
});
};
$scope.gridOptions = {
data: 'myData',
enableRowSelection: true,
enableCellEditOnFocus: true,
showSelectionCheckbox: true,
selectedItems: $scope.selectedRows,
columnDefs: [{
field: 'ID',
displayName: 'Id',
enableCellEdit: false
}, {
field: 'APP_ID',
displayName: 'Module ID',
enableCellEdit: false
}, {
field: 'RLDESC',
displayName: 'Role Description',
enableCellEdit: true
}, {
field: 'APDESC',
displayName: 'Module Description',
enableCellEdit: true
}, {
field: 'ZEND_DB_ROWNUM',
displayName: 'Record number',
enableCellEdit: false
}]
};
// fire it up
initializeGrid();
}
My complete json:
{
"_links": {
"self": {
"href": "http://xx.xx.xx.xx/coName/public/index.php/roles?page=1"
},
"describedBy": {
"href": "Some Fun Stuff"
},
"first": {
"href": "http://xx.xx.xx.xx/coName/public/index.php/roles"
},
"last": {
"href": "http://xx.xx.xx.xx/coName/public/index.php/roles?page=1"
}
},
"_embedded": {
"roles": [
{
"ID": 1,
"APP_ID": 1,
"RLDESC": "Admin",
"APDESC": "authLive",
"ZEND_DB_ROWNUM": "1"
},
{
"ID": 2,
"APP_ID": 1,
"RLDESC": "User",
"APDESC": "authLive",
"ZEND_DB_ROWNUM": "2"
},
{
"ID": 4,
"APP_ID": 1,
"RLDESC": "SuperUser",
"APDESC": "authLive",
"ZEND_DB_ROWNUM": "3"
}
]
},
"page_count": 1,
"page_size": 25,
"total_items": 3
}
Remove the following line from the gridOptions
data: 'myData'
Then in getRoles() use
$scope.gridOptions.data = myRolesData;
instead of
$scope.myData = myRoles.data._embedded.roles;
(Maybe you need $scope.myData for some other reason than the grid, but if not I think the above is all you need. I have not tested this live, but it should work.)