vue-chartjs in laravel,vuejs using API Axios - mysql

I am trying to show the all the companies in the Chart in Dashboard.vue regarding years but it does not show anything and I am trying since many days if someone could help me it will be so kind of him.
My API/Route is :
Route::apiResources(['company'=>'API\CompanyController']);
EmployeeController code is :
public function index(){return Employee::all();}
Code in Chart.vue is:
<script>
import { Line } from "vue-chartjs";
export default {
extends: Line,
data() {
return {
url: "api/company",
years: [],
labels: [],
data: ""
};
},
methods: {
getProducts() {
axios.get(this.url).then(response => {
this.data = response.data;
if (this.data) {
this.data.forEach(element => {
this.years.push(element.created_at);
this.labels.push(element.name);
});
this.renderChart(
{
labels: this.years,
datasets: [
{
label: "list of Companies ",
backgroundColor: "#f87979",
data: this.name
}
]
},
{ responsive: true, maintainAspectRatio: false }
);
} else {
console.log("NO DATA");
}
});
}
},
mounted() {
this.getProducts();
}
};
</script>
Code in app.js is :
Vue.component('chart-component', require('./components/Chart.vue'));
code in Dashboard is :
<template>
<div class="container">
<chart-component></chart-component>
</div>
</template>

I solved it the problem was that I did not put the .default so I amend it like below:
Vue.component('chart-component', require('./components/Chart.vue').default);

Related

Vue js table row with info

I want to see information when I click to row in the table. I tried #click, router:to but it didn't help. Maybe I should try to make list item instead of data-table?
html code:
<v-data-table v-scroll:#scroll-target="onScroll"
:items-per-page="-1"
hide-default-footer
dense
:headers="headers"
:items="companies"
item-key="name"
class="elevation-1"
></v-data-table>
Vue code below:
<script>
export default {
data: () => ({
companies: [
{
name: "Company",
status: "Active"
},
{
name: "Company2",
status: "Active"
},
{
name: "Company3",
status: "Active"
},
],
headers: [
{
text: "Company name",
align: "start",
sortable: false,
value: "name"
},
{ text: "Status", value: "status" }
],
methods: {
onScroll (e) {
this.companies = e.target.scrollTop
},
}
})
};
</script>
I am using vuetify library. Maybe this is a problem of vuetify and it has different command to make clickeble row in data-table?
Checkout the vuetify data table events: https://vuetifyjs.com/en/components/data-tables/
The first one there is click:row.
So you would have something like:
// template
<v-data-table #click:row="rowClicked"></v-data-table>
// script
export default {
methods: {
rowClicked (item) {
// show something or do your router stuff here
}
}
}
Hope that helps.

Access an axios data formatted as json from vue

I need to show data from a json response from get request. Vue part of my code is :
<script type="text/javascript">
var vm = new Vue({
el: '#app2',
delimiters: ['[[',']]'],
data: {
masa_data: {},
},
mounted: function() {
polling1=setInterval(function() {
axios.get('/order')
.then(function(response) {
vm.$data.masa_data = response.data;
})
}, 1000);
},
beforeDestroy () {
clearInterval(this.polling1)
}
});
</script>
masa_data comes from axios as below:
{ "Bahçe1": { "A": { "1": { "kisi_sayisi": "2", "siparisler": [ {
"adet": 2, "bolum": "drink", "satir": "Açık Çay" }, { "adet": 1,
"bolum": "tatli", "satir": "Kaymaklı Ekmek Kadayıfı" } ] },
When i want to show, for example, value of "kisi_sayisi", I could not figure out what to put inside html code below:
<p class="card-text">[[masa_data]]</p>
Try this.
<p class="card-text" v-if="Object.values(masa_data).length>0">[[masa_data.Bahce1.A['1']['kisi_sayisi'] ]]</p>
https://codepen.io/Pratik__007/pen/QWbjOxE?editors=1010

Load form data via REST into vue-form-generator

I am building a form, that needs to get data dynamically via a JSON request that needs to be made while loading the form. I don't see a way to load this data. Anybody out here who can help?
JSON calls are being done via vue-resource, and the forms are being generated via vue-form-generator.
export default Vue.extend({
template,
data() {
return {
model: {
id: 1,
password: 'J0hnD03!x4',
skills: ['Javascript', 'VueJS'],
email: 'john.doe#gmail.com',
status: true
},
schema: {
fields: [
{
type: 'input',
inputType: 'text',
label: 'Website',
model: 'name',
maxlength: 50,
required: true,
placeholder: companyList
},
]
},
formOptions: {
validateAfterLoad: true,
validateAfterChanged: true
},
companies: []
};
},
created(){
this.fetchCompanyData();
},
methods: {
fetchCompanyData(){
this.$http.get('http://echo.jsontest.com/key/value/load/dynamicly').then((response) => {
console.log(response.data.company);
let companyList = response.data.company; // Use this var above
}, (response) => {
console.log(response);
});
}
}
});
You can just assign this.schema.fields.placeholder to the value returned by the API like following:
methods: {
fetchCompanyData(){
this.$http.get('http://echo.jsontest.com/key/value/load/dynamicly').then((response) => {
console.log(response.data.company);
this.schema.fields.placeholder = response.data.company
}, (response) => {
console.log(response);
});
}
}

JSON data with angular2-highcharts

I want to create chart based on the JSON data.
I using angular2-highcharts my ChartsMain component looks like:
#Component({
moduleId: module.id,
selector: 'charts',
templateUrl: 'charts.html',
directives: [CHART_DIRECTIVES,]
providers: [DataService]
})
export class ChartsMain {
result: Data[];
constructor(DataService:DataService) {
DataService.getData().subscribe(res => this.result = res);
this.options = {
chart: {
type: "candlestick"
},
title: {
text: "JSON data"
},
xAxis: {
type: "category",
allowDecimals: false,
title: {
text: ""
}
},
yAxis: {
title: {
text: "Number"
}
},
series: [{
name: "Hour",
data: this.result
}]
};
}
options: Object;
And my DataService looks:
#Injectable()
export class DataService {
http: Http;
constructor(http: Http) {
this.http = http;
}
getData(): Observable<Array<Data>> {
return this.http.get('http://JSON-DATA')
.map(this.extractData)
.catch(this.handleError)
}
private extractData(res: Response) {
let body = res.json();
return body || { };
}
private handleError(error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
My chart
Where is a problem, why is chart empty? How do I fill the chart with JSON data. JSON data must be in any specific format?
A candlestick chart is typically used to present the open, high, low and close price over a period of time..
Sample expected JSON format looks like this-
[
[1250553600000,23.09,23.46,23.06,23.43],
[1250640000000,23.25,23.61,23.21,23.51],
[1250726400000,23.57,23.82,23.52,23.76],
[1250812800000,23.95,24.20,23.83,24.17],
[1251072000000,24.30,24.39,24.04,24.15],
[1251158400000,24.21,24.42,24.16,24.20],
[1251244800000,24.13,24.22,23.82,23.92],
[1251331200000,24.11,24.22,23.55,24.21],
[1251417600000,24.61,24.64,24.08,24.29],
[1251676800000,24.02,24.12,23.79,24.03],
]
Here is sample component with candlestick highchart-
import { Component } from '#angular/core';
import {JSONP_PROVIDERS, Jsonp} from '#angular/http';
import { CHART_DIRECTIVES } from 'angular2-highcharts';
#Component({
selector: 'high-chart',
directives: [CHART_DIRECTIVES],
providers: [JSONP_PROVIDERS],
template: `
<h2> This is HighChart CandleStick component </h2>
<chart type="StockChart" [options]="options3"></chart>
`
})
export class HighChartsComponent {
options3: Object;
constructor(jsonp : Jsonp) {
jsonp.request('https://www.highcharts.com/samples/data/jsonp.php?a=e&filename=aapl-ohlc.json&callback=JSONP_CALLBACK').subscribe(res => {
this.options3 = {
title : { text : 'CandleSticks' },
rangeSelector : {
selected : 1
},
series : [{
type : 'candlestick',
name : 'CandleSticks',
data : res.json(),
dataGrouping : {
units : [
[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]
]
},
tooltip: {
valueDecimals: 2
}
}]
};
});
}
EDIT:
In your case you are not setting chart options inside subscribe. You should set like this-
this._http.get('http://knowstack.com/webtech/charts_demo/data.json')
.map(this.extractData)
.subscribe((response) => {
this.options = {
title : { text : 'knowstack' },
series : [{
name : 'knowstack',
data : response.json()
}]
};
},
(error) => {
this.errorMessage = <any>error
});
Please note - data from knowstack will only work with simple charts (not candlestick)
EDIT 2: column chart
Please refer below configuration. This is how you can use column chart.
this.options1 = {
title : { text : 'simple column chart' },
series: [{
type : 'column',
data: [["Maths",15],["Physics",16],["Biology",18],["Chemistry",19]]
}]
};
EDIT 3: sample of key-value pair json
import { Component } from '#angular/core';
import { CHART_DIRECTIVES } from 'angular2-highcharts';
#Component({
selector: 'my-app',
directives: [CHART_DIRECTIVES],
styles: [`
chart {
display: block;
}
`]
template: `<chart [options]="options"></chart>`
})
class AppComponent {
constructor() {
var data = [{"key":"Math","value":98},{"key":"Physics","value":78},{"key":"Biology","value":70},{"key":"Chemistry","value":90},{"key":"Literature","value":79}];
this.options = {
title : { text : 'simple chart' },
xAxis: {
type: 'category'
},
series: [{
data: data.map(function (point) {
return [point.key, point.value];
})
}]
};
}
options: Object;
}
Ok it is work. I use service which in my first post, I just changed component: constructor(http: Http, jsonp : Jsonp, DataService:DataService) {
DataService.getData().subscribe(res => this.result = res);
http.request('').subscribe(res => {
this.options = {
chart: {
type: 'column'
},
plotOptions: {
column: {
zones: [{
value: 12,
},{
color: 'red'
}]
}
},
series: [{
data: this.result
}]
};
});
}
options: Object;
in this case json data: [{"key":"Math","value":98},{"key":"Physics","value":78},{"key":"Biology","value":70},{"key":"Chemistry","value":90},{"key":"Literature","value":79}]
How can I split this data like there http://www.knowstack.com/webtech/charts_demo/highchartsdemo4.html

aurelia bridge kendo grid refresh

I'm trying to use Aurelia KendoUi Bridge in my application.
In my code I have a service which returns a new KendoDataSource :
export class KendoDataSource {
ToKendoDataSource(data: any, recordCount: number, pageSize: number, currentPage: number): any {
return {
transport: {
read: (p) => {
p.success({ data: data, recordCount: recordCount });
}
},
pageSize: pageSize,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
schema: {
data: (result) => {
console.log('Transforming data to kendo datasource.');
return result.data;
},
total: (result) => {
return result.recordCount;
}
}
};
}
}
And this is my viewModel:
#inject(HttpService, KendoDataSource, EventAggregator)
export class GroupList {
grid: any;
gridVM: any;
datasource: any;
pageable: any;
subscriber: any;
paginationDetailsRequest: PaginationDetailsRequest;
test: string;
constructor(private httpService: HttpService, private kendoDataSource: KendoDataSource, private eventAggregator: EventAggregator) {
this.httpService = httpService;
this.kendoDataSource = kendoDataSource;
this.eventAggregator = eventAggregator;
this.paginationDetailsRequest = new PaginationDetailsRequest(4, 1);
this.GetGroups(this.paginationDetailsRequest);
this.datasource = {
transport: {
read: {
url: 'PersonGroup/GetGroups',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json'
},
parameterMap: function (data, type) {
if (type == "read") {
let paginationDetails = new PaginationDetailsRequest(data.pageSize, data.page);
if(data.sort && data.sort.length > 0){
paginationDetails.orderBy = data.sort[0].field;
paginationDetails.OrderDesc = (data.sort[0].dir == 'desc');
}
console.log(this.datasource);
return JSON.stringify(paginationDetails);
}
}
},
schema: {
data: "data.currentPageData",
total: "data.totalCount"
},
pageSize: 2,
serverPaging: true,
serverFiltering: true,
serverSorting: true
};
};
attached() {
this.subscriber = this.eventAggregator.subscribe('Search', response => {
this.search(response);
});
}
activate() {
this.pageable = {
refresh: true,
pageSizes: true,
buttonCount: 10
};
}
GetGroups(paginationDetails: PaginationDetailsRequest): void {
this.httpService.post('PersonGroup/GetGroups', paginationDetails)
.then(response => response.json())
.then(groups => {
console.log(groups);
if (groups.succeeded) {
this.datasource = this.kendoDataSource.ToKendoDataSource(groups.data.currentPageData, groups.totalCount, groups.pageSize, groups.currentPage);
this.grid.setDataSource(this.datasource); // initialize the grid
}
else {
//TODO: Show error messages on screen
console.log(groups.errors);
}
})
.catch(error => {
//TODO: Show error message on screen.
console.log(error);
});
}
search(searchDetails: Filter) {
console.log(searchDetails);
this.paginationDetailsRequest.filters.push(searchDetails);
console.log(this.paginationDetailsRequest);
this.GetGroups(this.paginationDetailsRequest);
}
detached() {
this.subscriber.dispose();
}
}
I understand that kendo does not have two-way data binding, But I'm trying to find a way to refresh the grid when I filter the data and the data source has changed.
Thanks.
I had this problem and found the solution by creating a new dataSource and assigning it to setDataSource, as follows... Note, getClients() is a search activated by a button click.
Here is the grid:
<ak-grid k-data-source.bind="datasource"
k-pageable.bind="{ input: true, numeric: false}"
k-filterable.bind="true"
k-sortable.bind="true"
k-scrollable.bind="true"
k-widget.bind="clientgrid"
k-selectable.bind="true">
<ak-col k-title="First Name" k-field="firstName" k-width="120px"></ak-col>
<ak-col k-title="Last Name" k-field="lastName" k-width="120px"></ak-col>
<ak-col k-title="Email Address" k-field="primaryEmail" k-width="230px"></ak-col>
</ak-grid>
And here is the code that updates the dataSource
public getClients()
{
console.log("ClientService.getClients");
this.clientService.getClients()
.then(result =>
{
this.clientList = result;
// the new datasource in the next line is displayed
// after the call to setDataSource(ds) below.
let ds: kendo.data.DataSource = new kendo.data.DataSource({
data: this.clientList,
schema: {
model: {
id: "id",
fields: {
firstName: { type: 'string' },
id: { type: 'number' },
lastName: { type: 'string' },
primaryEmail: { type: 'string' }
}
}
},
pageSize: 10
});
this.clientgrid.setDataSource(ds);
this.clientgrid.refresh();
})
.catch(err => console.log("Error returned from getClients " + err));
}
You don't really need to create a brand new datasource. To refresh the grid after changing the underlying data you can just replace the data element in the dataSource like so:
this.clientgrid.dataSource.data(this.datasource.data);