this is my service.ts
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { Headers } from '#angular/http';
#Injectable()
export class BarserviceService {
public http: Http;
people:any;
constructor(http: Http) {
this.http = http;
}
get() {
// return this.mediaItems;
let charts = this.http.get("http://localhost:3000/charts")
.map(response => { this.people = response.json()
console.log("pople", this.people)
});
return charts;
}
this is my barchart.component.ts
ngOnInit() {
// this.getEarthquakes();
this.options = {
chart: {
type: 'discreteBarChart',
height: 450,
margin : {
top: 20,
right: 20,
bottom: 50,
left: 55
},
x: function(d){return d.label;},
y: function(d){return d.value;},
showValues: true,
valueFormat: function(d){
return d3.format(',.4f')(d);
},
duration: 500,
xAxis: {
axisLabel: 'X Axis'
},
yAxis: {
axisLabel: 'Y Axis',
axisLabelDistance: -10
}
}
}
this.data =
[{
values: [
]
}
]
this.baroneService.get().subscribe(c => {
// console.log("pep",this.people);
// this.media = c.charts
console.log( "media",this.media = c.charts)
this.data = this.media
console.log("pep",this.data);});
this will be my json
{
"charts": [
{
"values": [
{
"label": "A",
"value": -29.765957771107
},
{
"label": "B",
"value": 0
} ]} ]}
am getting the json data in console pople in service.ts file but am not understanding how to get it in this.data in the component.ts file so i can display chart through json data and am getting an error in
console.log( "media",this.media = c.charts) in component.ts .can anyone help me with this.
You Can Inject The Service to The Constructer.
Like This.
import { Service Class Name } from 'location of service file';
Then You Can Inject to Constructer.
constructer(private nameofyourown:Service Class Name)
{
}
You Can use all The variables Declared inside The Service.
Here is The Syntax.
name used in constructer ex:
if i used like This.
Constructer(private name:serviceclassname)
you can used to call the variables like this.
name.variablename
variablename is declared inside service you can use it like the above syntax.
Related
this is my first question asked on stackoverflow!
I'm quite new on Vue.js and I am currently trying to display and interact with a node network graph using the v-network-graph component. I am struggling with using the EventHandler, because I didn't really got how to create it and interact with it. Should I initiate it within another instance and import it directly inside this one? Could you please help me understand how to manage the event handler ?
I tried the following code, expecting it to print in the console the node's id I clicked on:
<script lang="ts">
import { reactive, ref } from 'vue';
import * as vNG from 'v-network-graph';
import {
ForceLayout,
ForceNodeDatum,
ForceEdgeDatum,
} from 'v-network-graph/lib/force-layout';
const graph = ref<vNG.Instance>();
export default {
data() {
return {
nodes: { '': { name: '' } },
edges: { '': { source: '', target: '' } },
layouts: {
nodes: {
node0: {
x: 0,
y: 0,
fixed: true,
},
},
},
configs: reactive(
vNG.defineConfigs({
node: {
selectable: true,
label: {
direction: 'center',
color: '#eeeeee',
},
normal: {
radius: 48,
},
},
view: {
autoPanAndZoomOnLoad: 'fit-content',
minZoomLevel: 1,
maxZoomLevel: 2,
layoutHandler: new ForceLayout({
positionFixedByDrag: false,
positionFixedByClickWithAltKey: true,
}),
},
}),
),
};
},
methods: {
async getNodes() {
await fetch('http://127.0.0.1:5000/getNodes')
.then((response) => response.json())
.then((data) => { this.nodes = (data); });
},
async getEdges() {
await fetch('http://127.0.0.1:5000/getEdges')
.then((response) => response.json())
.then((data) => { this.edges = (data); });
},
},
beforeMount() {
this.getNodes();
this.getEdges();
const eventHandlers: vNG.EventHandlers = {
'node:click': ({ node }) => {
window.console.log(this.nodes[node]);
},
};
},
mounted() {
this.$refs.graph.fitToContents();
},
};
</script>
<template>
<v-network-graph
:nodes="nodes"
:edges="edges"
:configs="configs"
:layouts="layouts"
:event-handlers="eventHandlers"
ref="graph"
class="visualization"
/>
</template>
<style>
.visualization {
width: 100%;
height: 100vh;
border: 1px solid #000;
}
</style>
I've understood how to make it thanks to this post. Basically the documentation I was learning with is using Script Setup while I'm using the OptionAPI!
The actual answer:
The trick here is to not use the vNG.EventHandlers and to set the event handling Object directly in the data component, and the v-bind directive in the graph element.
The code (please note that I intentionally removed the useless code that was in the previous post to make a clearer answer):
<script lang="ts">
import { reactive, ref } from 'vue';
import * as vNG from 'v-network-graph';
const graph = ref<vNG.Instance>();
export default {
data() {
return {
nodes: reactive({ '': { name: '' } }),
edges: { '': { source: '', target: '' } },
click_event: {
'node:click': ({ node }) => {
window.console.log(this.nodes[node]);
},
},
},
},
};
</script>
<template>
<v-network-graph
:nodes="nodes"
:edges="edges"
:event-handlers="click_event"
ref="graph"
class="visualization"
/>
</template>
I am rendering a jspreadsheet component with data fetched from fastapi.
<template>
<h1>Synthèse évaluation fournisseur</h1>
<VueJSpreadsheet v-model="data.table" :options="myOption" />
{{ data.columns }}
</template>
<script>
import { reactive, onMounted, isProxy, toRaw, ref } from "vue";
import VueJSpreadsheet from "vue3_jspreadsheet";
import "vue3_jspreadsheet/dist/vue3_jspreadsheet.css";
export default {
components: {
VueJSpreadsheet,
},
setup() {
// var intervalID = setInterval(init, 3000);
var data = reactive({
table: [],
columns: [],
});
async function load_data() {
const response = await fetch("http://LOCALHOST:8080/supplier_overview");
return await response.json();
}
load_data().then((response)=>{
data.table=JSON.parse(response.result.data)
data.columns=(response.result.columns)
});
console.log(data.columns)
const myOption = ref({
columns: data.columns,
search: true,
filters: true,
includeHeadersOnDownload: true,
includeHeadersOnCopy: true,
defaultColAlign: "left",
tableOverflow: true,
tableHeight: "800px",
parseFormulas: true,
copyCompatibility: true,
});
return {
data,
myOption,
};
},
};
</script>
whereas data.columns is rendered correctly in the template, I cannot pass it to myOptions .
The proxy is empty with console.log(data.columns) whereas {{data.columns}} returns the correct array :
[ { "title": "period" }, { "title": "fournisseur" }, { "title": "Qualité" }, { "title": "Rques Qualité" }, { "title": "Logistique" }, { "title": "Rques Logistique" }, { "title": "Cout" }, { "title": "Rques Cout" }, { "title": "Système" }, { "title": "Rques Système" }, { "title": "Mot QLCS" }, { "title": "Note" }, { "title": "Rques" } ]
Any ideas why I cannot passed it correctly to myOptions ?
This problem has nothing to do with the variable myOptions
setup() {
async function load_data() {
const response = await fetch("http://LOCALHOST:8080/supplier_overview");
return await response.json();
}
//the function is async, 1 will be called after 2, so the result is empty
load_data().then((response)=>{
data.table=JSON.parse(response.result.data)
//1
data.columns=(response.result.columns)
});
//2
console.log(data.columns)
}
I have created a project with Vue. I'm trying to show some data through a chart using the ChartJs library, to capture the information I use axios. I've been getting this error since the beginning but I don't know what I'm missing, any idea?
async created() {
const { data } = await axios.get("https://covid19.mathdro.id/api/confirmed");
var c=0
for(var i=0;i<1000;i++){
if(data[i].countryRegion=="India"){
if (data[i].provinceState in this.labels){
continue
}
else{
this.labels.push(data[i].provinceState)
this.confirmed.push(data[i].confirmed)
c=c+1
if(c==28){
break
}
}
}
}
console.log(this.labels)
}
In the error message it also mentions this function which is in the LineChart.vue file
<template>
<canvas ref="chartLine" width="900px" height="250px"></canvas>
</template>
<script>
import Chart from 'chart.js';
export default {
props: {
label: {
type: Array
},
chartData: {
type: Array
},
},
async mounted() {
await new Chart(this.$refs.myChart, {
type: 'line',
data: {
labels: this.label,
datasets: [
{
label: 'CASES',
borderColor: 'rgba(245, 229, 27, 1)',
backgroundColor: 'rgba(255, 236, 139,0.2)',
data: this.chartData,
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
}
</script>
I made a VueJS 3 project with VueX to store the data.
When I print the variable data.doughnutChart.data in the following code it displays
{ "labels": [ "OK", "WARNING", "ERROR" ], "datasets": [ {
"backgroundColor": [ "#d4efdf", "#fdebd0", "#fadbd8" ], "data": [ 3,
1, 2 ] } ] }
But the graph doesn't use these data [3,1,2], the graph uses the values of the initialization in the index.js of VueX.
Here my code :
<template>
{{data.doughnutChart.data}}
<div style="height:200px;width: 200px; position:center">
<vue3-chart-js
:id="data.doughnutChart.id"
:type="data.doughnutChart.type"
:data="data.doughnutChart.data"
:options="data.doughnutChart.options"
></vue3-chart-js>
</div>
</template>
<script>
import Vue3ChartJs from '#j-t-mcc/vue3-chartjs'
export default {
name: 'App',
components: {
Vue3ChartJs,
},
beforeMount() {
this.$store.dispatch("getData");
},
computed: {
data() {
return {
doughnutChart: {
id: 'doughnut',
type: 'doughnut',
data: {
labels: ['OK', 'WARNING', 'ERROR'],
datasets: [
{
backgroundColor: [
'#d4efdf',
'#fdebd0',
'#fadbd8'
],
data: [this.$store.state.nbOk, this.$store.state.nbWarning, this.$store.state.nbError]
}
]
},
options:
{
plugins: {
legend: {
display: false
},
title: {
display: true,
text: 'Current situation'
}
},
}
}
}
}
}
}
</script>
I read the value in my index.js (VueX) :
import axios from 'axios'
import { createStore } from 'vuex'
export default createStore({
state: {
data: [],
nbError : 0,
nbWarning : 0,
},
actions: {
getData({commit}){
axios.get('http://localhost:8080/data/mock.json')
.then(res => {
commit('SET_DATA', res.data)
})}
},
mutations: {
SET_DATA(state, data){
state.data = data.data;
state.nbWarning = 0;
state.nbError = 0;
for (let i = 0; i < state.data.length; i++) {
if(state.data[i].status == 'WARNING'){
state.nbWarning += 1;
};
if(state.data[i].status == 'ERROR'){
state.nbError += 1;
};
};
}
})
However it works when, in my Vuejs project, I go in an other page and come back but not when I just open the project or refresh the page.
Do you know why ?
data property should be defined as computed in order to receive store changes:
<template>
{{data}}
</template>
<script>
export default {
data() {
return {
}
},
computed:{
data(){
return [this.$store.state.nbWarning, this.$store.state.nbError]
}
},
beforeMount() {
this.$store.dispatch("getData");
}
}
</script>
Im trying to display chart using chartjs by calling API, but unable to do so.
Here s my LineChart.vue:
<script>
import {Line, mixins} from 'vue-chartjs' // We specify what type of chart we want from vue-chartjs and the mixins module
const { reactiveProp } = mixins
export default { //We are extending the base chart class as mentioned above
extends: Line,
mixins: [reactiveProp],
data () {
return {
options: { //chart options
lineTension: 0,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
yAxes: [
{
scaleLabel: {
display: false
},
ticks: {
beginAtZero: true,
// eslint-disable-next-line no-unused-vars
callback (value, index, values) {
return `${value }%`
}
}
}
],
xAxes: [
{
type: 'time',
time: {
unit: 'month'
},
scaleLabel: {
display: true,
labelString: ''
}
}
]
}
}
}
},
mounted () {
// this.chartData is created in the mixin
this.renderChart(this.chartData, this.options)
}
}
</script>
And here is my Home.vue where i have imported the LineChart:
<template>
<div class="chart">
<line-chart :chart-data="datacollection"></line-chart>
</div>
</template>
<script>
import LineChart from './LineChart'
import axios from 'axios'
import DateTime from 'luxon'
export default {
data () {
return {
date: {},
challenge: {},
datacollection: {}
}
},
component: {LineChart},
created() {
this.fillData()
},
mounted () {
this.fillData()
},
methods: {
fillData () {
axios.get('https://my_api_goes_here')
.then(response => {
const results = response.data
const dateresult = results.map(a => a.date)
const challengeresult = results.map(a => a.challenge)
this.date = dateresult
this.challenge = challengeresult
this.datacollection = {
labels: [this.date].map(labels => DateTime.fromMillis(labels * 1000).toFormat('MMM yyyy')),
datasets: [
{
data: [this.challenge],
label: 'Africa',
borderColor: '#7367F0'
}
]
}
})
.catch(error => {
console.log(error)
})
}
}
}
</script>
Dont know why the chart did not appear even though my other resources have been loaded from the API call, when i checked out my console, this is what error im getting:
TypeError: results.map is not a function
Please check out my logic and let me where the error is.