I am really confused. How can I access data in a graph?
The below data is getting from server in service:
{
"data": [
{
"Prev2WkAnsweredNotifcn": 0,
"CrntYearNotifiedNotifcn": 0,
"CrntWkAnsweredNotifcn": 0,
"Prev1WkAnsweredNotifcn": 0,
"Prev2WkNotifiedNotifcn": 0,
"CrntWkNotifiedNotifcn": 0,
"Prev1WkNotifiedNotifcn": 0,
"Closed": "Closed",
"Prev3WkNotifiedNotifcn": 0,
"Open": "Open",
"Prev3WkAnsweredNotifcn": 0,
"CrntMonthNotifiedNotifcn": 0
}
]
}
Service:
getPosts(): Observable<any> {
return this._http.get('EscalationGraphData/')
.map(res => res.json().data)
.do(data => console.log(data[0]) // eyeball results in the console
}
Final component --> Here I have to access data and need to show it:
import {Component} from 'angular2/core';
import {CHART_DIRECTIVES, Highcharts} from 'angular2-highcharts';
//import {IncidentGraphService} from './incident-graph-service.ts';
import {EscalatedRightSideData} from './escalated-right-side.component.ts';
import {HttpService} from './http.service.ts';
//<incident-right-side-data></incident-right-side-data>
#Component({
selector: 'escalation-graph-component',
directives: [CHART_DIRECTIVES , EscalatedRightSideData]//, IncidentRightSideData],
providers: [HttpService]
//providers :[IncidentGraphService]
styles: [`
chart {
display: block;
width: 600px;
height: 300px;
margin: 0;
}
`]
template: `
<div class="row">
<div class="col-md-5">
<chart [options]="options">
<series>
<point (select)="onPointSelect($event)"></point>
</series>
</chart>
`
})
export class EscalationGraphComponent {
response: Array<any>;
ngOnInit() {
this.onGetPosts();
}
constructor(private _httpService: HttpService) {
this.options = {
series: [
{
name:'Monitored'
data: [29.9, 71.5, 106.4, 129.2], //[data.CrntWkNotifiedNotifcn , data.Prev1WkNotifiedNotifcn , data.Prev2WkNotifiedNotifcn , data.Prev3WkNotifiedNotifcn]
allowPointSelect: true
},
{
name:'UnMonitored'
data: [10, 20, 30, 40], //[data.CrntWkAnsweredNotifcn , data.Prev1WkAnsweredNotifcn,data.Prev2WkAnsweredNotifcn , data.Prev3WkAnsweredNotifcn ]
allowPointSelect: true
},
],
credits:{enabled:false},
};
}
options: Object;
onPointSelect (e) {
this.point = e.context.y;
}
onGetPosts() {
this._httpService.getPosts()
.subscribe(
response => this.response = response,
console.log("response"),
error => console.log(error);
)
}
}
Data class to hold data:
export class GraphData {
Prev2WkAnsweredNotifcn: number;
CrntYearNotifiedNotifcn: number;
CrntWkAnsweredNotifcn: number;
Prev1WkAnsweredNotifcn: number;
Prev2WkNotifiedNotifcn: number;
CrntWkNotifiedNotifcn: number;
Prev1WkNotifiedNotifcn: number;
Prev3WkNotifiedNotifcn: number;
Prev3WkAnsweredNotifcn: number;
Prev3WkAnsweredNotifcn: number;
CrntMonthNotifiedNotifcn : number;
Open:string;
Closed :string;
}
I need to store data from server to a GraphData object. And later want to access that data into component in series ---> data. See commented code in component.
Related
Im usiing My react typescript project for Ant design 4 table . so when i adding ant design Summary table, got a following error
TS2741: Property 'index' is missing in type '{ children: Element; colSpan: number; }' but required in type 'SummaryCellProps'.
any one know how to fix that issue.
Thanks
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Table, Typography } from 'antd';
const { Text } = Typography;
const columns = [
{
title: 'Name',
dataIndex: 'name',
},
{
title: 'Borrow',
dataIndex: 'borrow',
},
{
title: 'Repayment',
dataIndex: 'repayment',
},
];
const data = [
{
key: '1',
name: 'John Brown',
borrow: 10,
repayment: 33,
},
{
key: '2',
name: 'Jim Green',
borrow: 100,
repayment: 0,
},
{
key: '3',
name: 'Joe Black',
borrow: 10,
repayment: 10,
},
{
key: '4',
name: 'Jim Red',
borrow: 75,
repayment: 45,
},
];
const fixedColumns = [
{
title: 'Name',
dataIndex: 'name',
fixed: true,
width: 100,
},
{
title: 'Description',
dataIndex: 'description',
},
];
const fixedData = [];
for (let i = 0; i < 6; i += 1) {
fixedData.push({
key: i,
name: i % 2 ? 'Light' : 'Bamboo',
description: 'Everything that has a beginning, has an end.',
});
}
ReactDOM.render(
<>
<Table
columns={columns}
dataSource={data}
pagination={false}
bordered
summary={pageData => {
let totalBorrow = 0;
let totalRepayment = 0;
pageData.forEach(({ borrow, repayment }) => {
totalBorrow += borrow;
totalRepayment += repayment;
});
return (
<>
<Table.Summary.Row>
<Table.Summary.Cell>Total</Table.Summary.Cell>
<Table.Summary.Cell>
<Text type="danger">{totalBorrow}</Text>
</Table.Summary.Cell>
<Table.Summary.Cell>
<Text>{totalRepayment}</Text>
</Table.Summary.Cell>
</Table.Summary.Row>
<Table.Summary.Row>
<Table.Summary.Cell>Balance</Table.Summary.Cell>
<Table.Summary.Cell colSpan={2}>
<Text type="danger">{totalBorrow - totalRepayment}</Text>
</Table.Summary.Cell>
</Table.Summary.Row>
</>
);
}}
/>
</>,
document.getElementById('container'),
);
Had this issue yesterday as well, looking at the SummeryCellProps the rc-table team made index required. So I just added <Table.Summary.Row index={1}> you need to iterate through your pagedata to add the index of the that column
Angular 7 ngx-gallery
I was able to take data in json format without any errors, but ngx-gallery doesn't seem, it loaded in the element in the page details but the images and the ngx-gallery template do not appear ,
It may not be taking photos from the service, but didn't make a mistake,
here is my code :
import {
NgxGalleryOptions,
NgxGalleryImage,
NgxGalleryAnimation
} from "ngx-gallery";
#Component({
selector: "app-city-detail",
templateUrl: "./city-detail.component.html",
styleUrls: ["./city-detail.component.css"],
providers: [CityService]
})
export class CityDetailComponent implements OnInit {
constructor(
private activatedRoute: ActivatedRoute,
private cityService: CityService
) {}
city: City;
photos: Photo[] = []
galleryOptions: NgxGalleryOptions[];
galleryImages: NgxGalleryImage[];
ngOnInit() {
this.activatedRoute.params.subscribe(params => {
this.getCityById(params["cityId"]);
});
}
getCityById(cityId) {
this.cityService.getCityById(cityId).subscribe(data => {
this.city = data;
this.getPhotosByCity(cityId)
});
}
getPhotosByCity(cityId){
this.cityService.getPhotosByCity(cityId).subscribe(data=>{
this.photos = data;
this.setGallery();
})
}
getImages(){
const imageUrls= []
for(let i = 0;i<this.city.photos.length;i++){
imageUrls.push({
small:this.city.photos[i].url,
medium:this.city.photos[i].url,
big:this.city.photos[i].url
})
}
return imageUrls;
}
setGallery(){
this.galleryOptions = [
{
width: '100%',
height: '400px',
thumbnailsColumns: 4,
imageAnimation: NgxGalleryAnimation.Slide
},
// max-width 800
{
breakpoint: 800,
width: '100%',
height: '600px',
imagePercent: 80,
thumbnailsPercent: 20,
thumbnailsMargin: 20,
thumbnailMargin: 20
},
// max-width 400
{
breakpoint: 400,
preview: false
}
];
this.galleryImages = this.getImages()
}
}
Template:
<ngx-gallery *ngIf="galleryImages" [options]="galleryOptions" [images]="galleryImages"></ngx-gallery>
this tutorial is complete
https://github.com/lukasz-galka/ngx-gallery-demo/blob/master/src/app/app.component.ts
use method addImage for your problem
help this image
private loadAll() {
this.imageService.getAllImage).subscribe(result => {
this.addImage(result);
});
}
addImage(images: any[]): void
images.forEach(image=>{
this.onlyPreviewExample.images.push(this.getImage(this.getRandomInt(1,2),doc));
});
}
private getImage(index: number, image?: any): NgxGalleryImage {
return {
big: 'imageUrl'
}
}
private getImages(): NgxGalleryImage[] {
let images = new Array<NgxGalleryImage>();
return images;
}
private getRandomInt(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
ngOnInit() {
this.ngxGalleryModel = new Array<NgxGalleryModel>();
this.ngxGalleryModel.push(
this.onlyPreviewExample = new NgxGalleryModel('Only preview', this.getImages(), [{
image: false,
thumbnails: false,
previewCloseOnClick: true,
previewCloseOnEsc: true,
previewZoom: true,
previewRotate: true,
// previewDownload: true,
previewFullscreen: true,
previewKeyboardNavigation: true,
arrowNextIcon: "fa fa-arrow-left",
arrowPrevIcon: "fa fa-arrow-right",
fullscreenIcon: "fa fa-arrows-alt",
width: '0px',
height: '0px'
}])
)
}
#ViewChild('onlyPreviewGallery', {static: false}) onlyPreviewGallery: NgxGalleryComponent;
ngxGalleryModel: NgxGalleryModel[];
onlyPreviewExample: NgxGalleryModel;
I want to apply a filter for the whole search and date range filter for material data table in angular 7.
I know that filter and filter predicate cannot be used together, but please tell me if there is an alternative.
I have already implemented the dynamic whole table search filter and now I wanted to filter the data source table with a date range. So, I implemented the filter predicate with that. But, now my whole search filter is not working.
import { Component, OnInit, ViewChild } from '#angular/core';
import * as Chartist from 'chartist';
import { ActivatedRoute } from '#angular/router';
import { MatPaginator, MatTableDataSource, MatSort } from '#angular/material';
import { FormGroup, FormControl } from '#angular/forms';
#Component({
selector: 'app-seller',
templateUrl: './seller.component.html',
styleUrls: ['./seller.component.css']
})
export class SellerComponent implements OnInit {
public state_name: any;
displayedColumns: string[] = ['position', 'id', 'date', 'name', 'address', 'city', 'state', 'amount'];
// tslint:disable-next-line: no-use-before-declare
dataSource = new MatTableDataSource(ELEMENT_DATA);
filterForm = new FormGroup({
fromDate: new FormControl(),
toDate: new FormControl(),
});
get fromDate() { return this.filterForm.get('fromDate').value; }
get toDate() { return this.filterForm.get('toDate').value; }
#ViewChild(MatPaginator) paginator: MatPaginator;
#ViewChild(MatSort) sort: MatSort;
constructor( private route: ActivatedRoute) {
this.dataSource.filterPredicate = (data) => {
if (this.fromDate && this.toDate) {
return new Date(data.date).getTime() >= this.fromDate.getTime() && new Date(data.date).getTime() <= this.toDate.getTime();
}
return true;
}
}
startAnimationForLineChart(chart: any) {
let seq: any, delays: any, durations: any;
seq = 0;
delays = 80;
durations = 500;
chart.on('draw', function(data: any) {
if (data.type === 'line' || data.type === 'area') {
data.element.animate({
d: {
begin: 600,
dur: 700,
from: data.path.clone().scale(1, 0).translate(0, data.chartRect.height()).stringify(),
to: data.path.clone().stringify(),
easing: Chartist.Svg.Easing.easeOutQuint
}
});
} else if (data.type === 'point') {
seq++;
data.element.animate({
opacity: {
begin: seq * delays,
dur: durations,
from: 0,
to: 1,
easing: 'ease'
}
});
}
});
seq = 0;
};
ngOnInit() {
// Initialize the chart
const dataCompletedTasksChart: any = {
labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
series: [
[230, 750, 450, 300, 280, 240, 200, 190]
]
};
const optionsCompletedTasksChart: any = {
lineSmooth: Chartist.Interpolation.cardinal({
tension: 0
}),
low: 0,
high: 1000,
chartPadding: { top: 0, right: 0, bottom: 0, left: 0}
}
const completedTasksChart = new Chartist.Line('#completedTasksChart', dataCompletedTasksChart, optionsCompletedTasksChart);
this.startAnimationForLineChart(completedTasksChart);
// Get state name from url
const name = this.route.snapshot.paramMap.get('state');
this.state_name = name;
// Initialize the pagination
this.dataSource.paginator = this.paginator;
// Initialize the sorting
this.dataSource.sort = this.sort;
}
// // Gets the total amount of all transactions
// getTotalAmount() {
// // tslint:disable-next-line: no-use-before-declare
// return ELEMENT_DATA.map(t => t.amount).reduce((acc, value) => acc + value, 0);
// }
// Whole table search filter
applySearchFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
}
// DateRange filter
applyDateFilter() {
this.dataSource.filter = '' + Math.random();
}
}
export interface PeriodicElement {
position: number;
id: any;
date: any;
name: string;
address: any;
city: string;
state: string;
amount: any;
}
const ELEMENT_DATA: any[] = [];
for (let i = 1; i <= 100; i++) {
const data = {
position: i,
id: 'QWERTY' + (i * 2),
date: '04/' + (i + 1) + '/2019',
name: 'Joshi Chemist',
address: 'W-980/8, Sainik Farm, New Delhi-110062',
city: 'New Delhi',
state: 'DELHI',
amount: i * 2300
};
ELEMENT_DATA.push(data);
}
Both the filter working simultaneously.
I have created a chart module using Angular2-highcharts but when I try to run the application I am getting the followoing error.
ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'options' since it isn't a known property of 'chart'. ("
<!-- <p text-center>Kye Info Page under construction</p> -->
<chart [ERROR ->][options]="chartOptions" type="chart"></chart>
</ion-content>
"): ng:///KeyinfoPageModule/KeyinfoPage.html#27:9
'chart' is not a known element:
1. If 'chart' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '#NgModule.schemas' of this component. ("
<ion-content>
Code
1. app.module.ts
import { ChartModule } from 'angular2-highcharts';
import * as highcharts from 'Highcharts';
imports: [
---------
ChartModule.forRoot(highcharts)
],
2. html File
<ion-content>
<chart [options]="chartOptions" type="chart"></chart>
</ion-content>
3. .ts file
export class KeyinfoPage {
chartOptions:any;
constructor(public navCtrl: NavController) {
}
ionViewDidLoad() {
this.chartOptions={chart: {
type: 'area'
},
title: {
text: 'US and USSR nuclear stockpiles'
},
subtitle: {
text: 'Source: <a href="http://thebulletin.metapress.com/content/c4120650912x74k7/fulltext.pdf">' +
'thebulletin.metapress.com</a>'
},
xAxis: {
allowDecimals: false,
labels: {
formatter: function () {
return this.value; // clean, unformatted number for year
}
}
},
yAxis: {
title: {
text: 'Nuclear weapon states'
},
labels: {
formatter: function () {
return this.value / 1000 + 'k';
}
}
},
tooltip: {
pointFormat: '{series.name} produced <b>{point.y:,.0f}</b><br/>warheads in {point.x}'
},
plotOptions: {
area: {
pointStart: 1940,
marker: {
enabled: false,
symbol: 'circle',
radius: 2,
states: {
hover: {
enabled: true
}
}
}
}
},
series: [{
name: 'USA',
data: [null, null, null, null, null, 6, 11, 32, 110, 235, 369, 640,
1005, 1436, 2063, 3057, 4618, 6444, 9822, 15468, 20434, 24126,
27387, 29459, 31056, 31982, 32040, 31233, 29224, 27342, 26662,
26956, 27912, 28999, 28965, 27826, 25579, 25722, 24826, 24605,
24304, 23464, 23708, 24099, 24357, 24237, 24401, 24344, 23586,
22380, 21004, 17287, 14747, 13076, 12555, 12144, 11009, 10950,
10871, 10824, 10577, 10527, 10475, 10421, 10358, 10295, 10104]
}, {
name: 'USSR/Russia',
data: [null, null, null, null, null, null, null, null, null, null,
5, 25, 50, 120, 150, 200, 426, 660, 869, 1060, 1605, 2471, 3322,
4238, 5221, 6129, 7089, 8339, 9399, 10538, 11643, 13092, 14478,
15915, 17385, 19055, 21205, 23044, 25393, 27935, 30062, 32049,
33952, 35804, 37431, 39197, 45000, 43000, 41000, 39000, 37000,
35000, 33000, 31000, 29000, 27000, 25000, 24000, 23000, 22000,
21000, 20000, 19000, 18000, 18000, 17000, 16000]
}]
}
console.log('ionViewDidLoad KeyinfoPage');
}
viewDashboard(){
this.navCtrl.setRoot('DashboardPage')
}
}
Please help me to solve this issue. I have found several questions like this but none of them helped me to solve this error. I am following this video to create the charts
https://www.youtube.com/watch?v=FSg8n5_uaWs&index=2&list=LLTJRcsGtG-ZMAf9dklVIikA&t=610s
keyinfo.module.ts
import { NgModule } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { KeyinfoPage } from './keyinfo';
import { ChartModule } from 'angular2-highcharts';
import * as highcharts from 'highcharts';
#NgModule({
declarations: [
KeyinfoPage,
],
imports: [
IonicPageModule.forChild(KeyinfoPage),
ChartModule
],
})
export class KeyinfoPageModule {}
You can set import the HighChartsModule in the IonicPageModule in which it is used instead of the app.module.ts
import { ChartModule } from 'angular2-highcharts';
import * as highcharts from 'highcharts';
#NgModule({
declarations: [
KeyinfoPage,
],
imports: [
IonicPageModule.forChild(KeyinfoPage),
ChartModule.forRoot(highcharts)
],
})
export class KeyinfoPageModule {}
I'm using angular 2, firebase and ng2-highcharts.
I assign data after I receive them from firebase like so :
this.items = af.database.list('/items');
this.optionsAsync = this.items.map(data => {
this.options.series[0].data = data.map(item => ([item.x, item.y]));
return this.options;
});
Then in my view template I have :
<div [ng2-highcharts]="optionsAsync | async"></div>
This is working fine at first load. But unfortunately when new data are received chart is not updated. Any idea ?
I found a solution by referencing highcharts component with #ViewChild like so :
in component class :
import { ViewChild, Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css'],
directives: [Ng2Highcharts]
})
export class AppComponent {
#ViewChild(Ng2Highcharts)
chartElement: Ng2Highcharts;
private chartData = {
chart: {
zoomType: 'x'
},
colors: ['rgba(255,0,255,1)'],
title: {
text: 'Items'
},
credits: '',
series: [{
type: 'area',
name: 'Items',
data: []
}]
};
chartData$ = new Subject();
ngOnInit() {
this.items.subscribe((data: any) => {
this.chartData.series[0].data = data.map(item => ([item.x, parseFloat(item.y)]) );
this.chartData$.next(this.chartData);
if(this.chartElement && this.chartElement.chart) {
var serieRef = this.chartElement.chart.series[0];
serieRef.setData(this.chartData.series[0].data);
}
});
}
}