Labels string from Asp.net does not distributed in the highchart - javascript

I try to make a pie highchart with data from Asp.Net and when i run the program the labels are not distributed individually,i use the same method for data array and i didn't have this issue there.
This is a representation of the graph : https://jsfiddle.net/rk0t4ghc/1/ ,i did the dataLabel array to reproduce the data from Asp.net.
Can you please help me?
import { Component, OnInit, Input } from '#angular/core';
import * as Highcharts from 'highcharts';
import { Order } from 'src/app/shared/order';
import {Customer} from 'src/app/shared/customer';
import {SalesDataService} from '../../services/sales-data.service';
import _ from 'lodash';
#Component({
selector: 'app-pie-chart',
templateUrl: './pie-chart.component.html',
styleUrls: ['./pie-chart.component.css']
})
export class PieChartComponent implements OnInit {
constructor(private _salesDataService:SalesDataService) { }
#Input() inputData:any;
#Input() limit:number;
ngOnInit() {
this.parseChartData(this.inputData,this.limit);
}
parseChartData(res:any,limit? :number){
console.log('response:',res);
const allData=res.slice(0,limit);
console.log('allData(slice):', allData);
Highcharts.chart('container2',{
chart:{
events:{
load(){
const chart=this;
chart.series[0].points.forEach((point)=>
point.update({
name:allData.map(x=>_.values(x)[0])
}),false);
chart.redraw();
}
}
},
tooltip:{
pointFormat: '{name}: <b>{point.percentage:.1f}%</b>'
},
series:[{
type:'pie',
showInLegend:true,
"data":allData.map(x=>_.values(x)[1])
}]
})
}
}

It is happening because you are assigning the entire array as a point name instead of a certain element of the array. (name: array, instead of a name: array[index])
Live demo:
https://jsfiddle.net/BlackLabel/yLfq207n/
load() {
dataLabels=['Name1','Name2','Name3','Name4']
const chart = this;
chart.series[0].points.forEach((point, index) => point.update({
name:dataLabels[index]
}), false);
chart.redraw();
}

Related

Implementing a choropleth chart in Anguar 2+ using chartjs-chart-geo

I need to create a geo chart and I have installed the chartjs-chart-geo to implement a chart that simple show the total sales per state.
I got this error when trying to fetch the features from the topojson object and I got stack in here. Can any of you please help me ?
Error:
Property 'features' does not exist on type 'Feature<Point, GeoJsonProperties>'.
Here's my unfinish component code:
import { Component, OnInit } from '#angular/core';
import { DashboardService } from '../../../modules/dashboard.service';
import { Chart, registerables } from 'chart.js';
import { ChoroplethController, GeoFeature, ColorScale, ProjectionScale } from 'chartjs-chart-geo';
import * as ChartGeo from 'chartjs-chart-geo'
import ChartDataLabels from 'chartjs-plugin-datalabels';
// register controller in chart.js and ensure the defaults are set
Chart.register(ChoroplethController, GeoFeature, ColorScale, ProjectionScale);
Chart.register(...registerables);
Chart.register(ChartDataLabels);
// Get the topojson file examples
const url = 'https://unpkg.com/world-atlas#2.0.2/countries-50m.json';
// const url = 'https://unpkg.com/us-atlas/states-10m.json';
#Component({
selector: 'quotes-by-state',
templateUrl: './quotes-by-state.component.html',
styleUrls: ['./quotes-by-state.component.css']
})
export class QuotesByStateComponent implements OnInit {
chart:any;
constructor(private dashService: DashboardService) { }
ngOnInit(): void {
// Prepare chart
this.createChart();
}
// Create chart component
createChart() {
// fetch('https://unpkg.com/us-atlas/states-10m.json').then((r) => r.json()).then((us) => {
// const nation = ChartGeo.topojson.feature(us, us.objects.nation).features[0];
// const states = ChartGeo.topojson.feature(us, us.objects.states).features;
fetch(url).then((result) => result.json()).then((datapoint) => {
// Get ChartGeo features from json
const nation = ChartGeo.topojson.feature(datapoint, datapoint.objects.countries).features;
this.chart = new Chart('geo-chart', {
type: 'choropleth',
data: {
labels: ['a', 'b', 'c'],
datasets: [
{
label: 'Contries',
outline: nation,
data: null, //states.map(country => ({feature: country, value: Math.random() * 100})),
},
]
},
options: {
responsive: true,
}
});
});
}
}

how to get the value of the clicked bar in Stacked Bar Chart.Js?

I am working in an Angular project where I am using chart.js.
I did console.log(this.myChart) three times.
at line number 21 and 30 its working fine but on line number 33 it's showing undefined.
why I am not able access this.myChart from onClickBar() method.
how can I get clicked bar info?
import { Component, Input, OnInit } from '#angular/core';
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);
#Component({
selector: 'app-chart',
templateUrl: './chart.component.html',
styleUrls: ['./chart.component.scss']
})
export class ChartComponent implements OnInit {
#Input() chartData:any;
canvas:any
myChart:any;
constructor() {
}
ngAfterViewInit(){
this.canvas = document.getElementById('canvas');
this.createChart();
console.log(this.myChart);
this.canvas!.onclick = this.onClickBar;
}
ngOnInit(): void {
}
createChart(){
this.myChart = new Chart("canvas", this.chartData);
console.log(this.myChart);
}
onClickBar(){
console.log(this.myChart);
}
}

Blank results when iterating through a non-empty array in angular template

EDIT: I made changes in the push method but it still did not work
I am making get request to an api and pushing each of the responses to an array. The array is visible when logged to console. On printing the length of the array in the template length comes out to be 5. But when I try to iterate through it using ngFor no output is being displayed
Service
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import {Quote} from 'src/app/models/quote';
#Injectable({
providedIn: 'root'
})
export class StockpriceService {
url1='https://financialmodelingprep.com/api/v3/quote-short/';
url2='?apikey=efa24b272821b542c459557332c02a1e';
constructor(private http:HttpClient) {
}
//alpha apikey="VETRGM94G70WQGX9";
getQuote(symbol:string) //load data from api
{
return this.http.get<Quote>(this.url1 + symbol + this.url2);
}
}
ts file
import { Component, OnInit } from '#angular/core';
import{Quote} from 'src/app/models/quote';
import{StockpriceService} from 'src/app/services/stockprice.service';
import { timer } from 'rxjs';
#Component({
selector: 'app-stocks',
templateUrl: './stocks.component.html',
styleUrls: ['./stocks.component.css']
})
export class StocksComponent implements OnInit {
stocks: Array<Quote>=[];
symbols=['AAPL', 'GOOG', 'FB', 'AMZN', 'TWTR'];
constructor(private serv:StockpriceService) { }
ngOnInit(): void {
this.symbols.forEach(symbol => {
this.serv.getQuote(symbol).subscribe(
(data:Quote)=>{
console.log(data);
this.stocks.push(
{
symbol:data.symbol,
price:data.price,
volume:data.volume
}
);
}
)
});
console.log('stocks array is')
console.log(this.stocks);
}
}
Template
<div *ngFor="let stock of stocks">
{{stock.symbol}}
{{stock.price}}
</div>
sample api response
[ {
"symbol" : "AAPL",
"price" : 126.81380000,
"volume" : 36245456
} ]
Accordingly I have an interface defined for it as
export interface Quote{
symbol:string;
price:number;
volume:number;
}
This will work fine.
this.serv.getQuote(symbol).subscribe((data: Quote[]) => {
console.log(data);
this.stocks.push(...data);
});

Change variable values through getter Typescript Angular 2

I'm trying to change the value in a Variable if the recieved content from a Json is empty. My approach is it to alter my getter Method. For some reasons it seems like the getter Method doesn't get called and it changes nothing, even though I make a call on it. Maybe you Guys can help me.
Here I try to customise my getter, but at runtime it doesn't get used:
export class Chart {
private _options: any;
get options(): any {
if (this._options){
this._options = {rotation: Math.PI, circumference: Math.PI};
return this._options;
} else {
console.log(this._options);
return this._options;
}
}
}
And here is my component.ts class where I try to use this Variable:
import {Component, Input, OnInit} from '#angular/core';
import {Chart} from "../main-content/entity/dashboard-config-fetcher";
#Component({
selector: 'app-chart',
templateUrl: './chart.component.html',
styleUrls: ['./chart.component.css']
})
export class ChartComponent implements OnInit {
#Input()
chart: Chart;
public options: any;
constructor() { }
ngOnInit() {
this.options = this.chart.options;
}
}
Thanks in Advance
If i understood you correctly I think ur missing a !
if (this._options) --> if(!this.options)
Otherwise you will return undefined if there is nothing stored in the _options variable

Why does #Output create circular json error?

Trying to catch an event emitted from my quantity-component
When I take away the #Output decorator everything works fine, but when I include it to catch the event I get this error:
EXCEPTION: Error in ./QuantityComponent class
QuantityComponent - inline template:0:567 caused by: Converting
circular structure to JSONErrorHandler.handleError #
...
ORIGINAL EXCEPTION: Converting
circular structure to JSON
What am I doing wrong?
// item-component.ts
import {Component, Input, Output, EventEmitter} from '#angular/core';
#Component({
selector: 'item-component',
template: '<quantity-component [initialQuantity]="initialQuantity" (change)="myValueChange($event)" ></quantity-component>'
})
export class ItemComponent {
myValueChange($event){
console.log($event);
}
}
// quantity-component.ts
import {Component, Input, Output, EventEmitter} from '#angular/core';
#Component({
selector: 'quantity-component',
templateUrl: 'quantity.component.html'
})
export class QuantityComponent {
#Input() item: string;
#Input('initialQuantity') counterValue = 0;
#Output('change') counterChange: EventEmitter<any> = new EventEmitter();
increase() {
this.counterValue++;
this.counterChange.emit({
value: this.counterValue
})
}
decrease() {
this.counterValue--;
this.counterChange.emit({
value: this.counterValue
})
}
}

Categories