Dynamic Highstock Chart

In this post, we are going to implement dynamic Highstock chart with Angular8 and ASP.Net Core. Previous post on Highchart that will help, please have an overview by following the link: https://shashangka.com/2018/06/15/dynamic-highchart-asp-net-core-angular6

Client Side:

Let’s add frontend packages by modifying package.json file.

Dependencies:

"angular-highcharts": "9.0.9",
"highcharts": "8.0.4"

Dev Dependencies:

"/highcharts": "^7.0.0",

Systemjs Config:

'angular-highcharts': 'npm:angular-highcharts/bundles/angular-highcharts.umd.js',
'highcharts': 'npm:highcharts/highstock.src.js',

Manage Packages:

gulp.src('./node_modules/angular-highcharts/**/*.js')
    .pipe(gulp.dest(root_path.package_lib + 'angular-highcharts'));

gulp.src('./node_modules/highcharts/**.js')
    .pipe(gulp.dest(root_path.package_lib + 'highcharts'));

Root Module:

import { ChartModule } from 'angular-highcharts';

Below is the updated code snippet in module.ts.

({
    imports: [
        ChartModule
    ]
})

Chart Component:

import { Component, OnInit } from '/core';
import { Title } from '/platform-browser';
import { DataService } from '../shared/service';
import { StockChart } from 'angular-highcharts';

({
    selector: 'app-home',
    templateUrl: './app/home/component.html',
    providers: [DataService]
})

export class HomeComponent implements OnInit {
    public res: any;
    public resmessage: string;
    public title: any;
    public chartstock: StockChart;
    public chartUrl: string = 'api/chart/getChartData';

    constructor(
        private titleService: Title,
        private _dataService: DataService) {
    }

    ngOnInit() {
        this.titleService.setTitle("Home-Chart");
        this.getChart();
    }

    getChart() {
        var getchartUrl = this.chartUrl;
        var dataService = this._dataService;

        //Chart
        var time = (new Date()).getTime();
        var totalPoint = 0;
        this.chartstock = new StockChart({
            chart: {  
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false,
                backgroundColor: null,
                marginRight: 10,
                events: {
                    load: function () {                 
                        var series = this.series[0];
                        setInterval(function () {  
                             dataService.get(getchartUrl)
                            .subscribe(
                                response => {
                                    var resdata = response[0]
                                    if(response != null)
                                    {
                                        var x = resdata.sensTimeMilisec, y = resdata.sensValue;
                                        //var x = (new Date()).getTime(), y = Math.round(Math.random() * 100);
                                        series.addPoint([x, y], true, false);  

                                        //Show Console to UI
                                        console.log(totalPoint+". Client Data:"+time +"-::::::-API Data:"+ x +" "+y);
                                        var logger = document.getElementById('log');
                                        console.log = function () {
                                            for (var i = 0; i < arguments.length; i++) {
                                                if (typeof arguments[i] == 'object') {
                                                    logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(arguments[i], undefined, 2) : arguments[i]) + '
'; } else { logger.innerHTML += arguments[i] + '
'; } } } totalPoint++; } }, error => { console.log(error); } ); }, 1000); } } }, time: { useUTC: false }, rangeSelector: { buttons: [{ count: 1, type: 'minute', text: '1M' }, { count: 5, type: 'minute', text: '5M' }, { type: 'all', text: 'All' }], inputEnabled: false, selected: 2 }, title: { text: 'Highstock Live Data [Angular-ASP.NETCore]' }, subtitle: { text: 'Displaying data points in Highcharts Stock' }, navigator: { enabled: true, xAxis: { type: 'datetime', // tickWidth: 0, // lineWidth: 0, // gridLineWidth: 1, // tickPixelInterval: 200, labels: { format: '{value:%e%b-%y %H:%M:%S %p}', align: 'center', style: { color: '#F60' } } } }, exporting: { enabled: false }, scrollbar: { barBackgroundColor: 'gray', barBorderRadius: 7, barBorderWidth: 0, buttonBackgroundColor: 'gray', buttonBorderWidth: 0, buttonBorderRadius: 7, trackBackgroundColor: 'none', trackBorderWidth: 1, trackBorderRadius: 8, trackBorderColor: '#CCC' }, xAxis: { type: 'datetime', labels: { format: '{value:%e%b-%y %H:%M:%S %p}', rotation: 20, align: 'left', style: { color: '#000' } }, }, plotOptions: { spline: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true } } }, series: [{ name: 'Value', type: 'spline', tooltip: {xDateFormat: '%e%b-%y %H:%M:%S %p'}, data: [] }] }); } }

Component Html:

Server Side:

//GET: api/chart/getChartData
[HttpGet("[action]")]
public async Task getChartData()
{
    object resdata = null; 
    try
    {
        List _list = new List();
        var sensData = await timeTicker.getSensData();
        _list.Add(sensData);
        resdata = _list;
    }
    catch (Exception) { }
    return resdata;
}

Random Data:

static int? _sensValue = 0;
static long? _datetimeMilliseconds = 0;

public static Task getSensData()
{
    return Task.Run(() =>
    {
        _sensValue = RandomNumber(1, 1000);
        _datetimeMilliseconds = TimeMilliseconds();
        SensData objdata = new SensData()
        {
            SensTimeMilisec = _datetimeMilliseconds,
            SensValue = _sensValue
        };

        return objdata;
    });
}

static long TimeMilliseconds()
{
    return new DateTimeOffset(DateTime.Now).ToUnixTimeMilliseconds();
}

static int RandomNumber(int min, int max)
{
    Random random = new Random();
    return random.Next(min, max);
}

OutPut:

For more information please follow:

Author:

Since March 2011, have 8+ years of professional experience on software development, currently working as Senior Software Engineer at s3 Innovate Pte Ltd.

Leave a Reply