Posts

....
Technical Blog for .NET Developers ©

Wednesday, July 3, 2024

Angular: HighCharts & SignalR

In this post we make a basic implementation of a graphic library, connected in real time with SignalR hub

High Charts Demos

The application is displaying data on the chart, generated from a SignalR hub, to test the versatility of implementation of this graphic library



The graph component has the next code, with html and scss styles

It is very important to implement the event chartInstance, to obtain a reference to the graphic chart

 
import {Component, EventEmitter, OnInit} from '@angular/core';
import * as Highcharts from 'highcharts';

@Component({
    selector: 'line-chart-component',
    templateUrl: 'line-chart-component.html',
    styleUrls: ['line-chart-component.scss']
})
export class LineChartComponent implements OnInit {

    Highcharts: typeof Highcharts = Highcharts;
    chartOptions!: Highcharts.Options;    
    updateFlag = false;
  
    data: number[] = [];
    categories: string[] = [];

    the_chart!: Highcharts.Chart;

    onChartInstance(chart: Highcharts.Chart)  : void {

        this.the_chart = chart;
    }

    ngOnInit(): void {
  
        this.chartOptions = {     
            title: {
              text: 'Demo'
            } ,                
            xAxis: {
                categories: this.categories
            },            
            series: [{
                type: 'line',
                data: this.data,                
                name: 'demo'
              }],            
          };              
    }
    

    addData(category: string, data: number) {

       this.the_chart.xAxis[0].categories.push(category);
       this.the_chart.series[0].addPoint(data);
    }    
  
}


 
<div class="divChart">
  <highcharts-chart 
    [Highcharts]="Highcharts"
    [options]="chartOptions"
    [(update)]="updateFlag"
    (chartInstance)="onChartInstance($event)">
  </highcharts-chart>    
</div>


 
.divChart {
    display:flex; 
    justify-content: center; 
    align-items: center; 
    flex-direction: column;
}



The SignalR connection and configuration is released in the event ngOnInit of the component

 
    ngOnInit(): void {

        this.signalr.startConnection();
        this.addSignalRListeners();        
    }    

    addSignalRListeners = (): void => {

        this.signalr.addListener('newConnection', this.onNewConnection );
        this.signalr.addListener('broadcastMessage', this.onBroadcastMessage );
    }

    onNewConnection = (connection: any): void  => {
        console.log(connection);
    }

    onBroadcastMessage = (message: any): void => {
        this.lineChart.addData(message.demo, message.total);
        console.log(message);
    }  
    


 
    public startConnection = () => {

        this.hubConnection = new HubConnectionBuilder()
                                .withUrl(environment.hubUrl, {
                                    accessTokenFactory: () => {
                                        return localStorage.getItem('token')!
                                    }
                                })                                
                                .configureLogging(LogLevel.Information)
                                .withStatefulReconnect()
                                .build();

        this.hubConnection
            .start()
            .then(() => console.log('Connection started'))
            .catch(err => console.log('Error while starting connection: ' + err)
            );
    }

    public addListener(evtName: string, fn: (result: any) => void) : void {

        this.hubConnection.on(evtName, fn);                        
    }   
  


METHOD SOFTWARE 2024 ©