Live Data Chart
Implement a live updating chart in Angular using Chart.js and WebSocket to stream real-time data for visualization.
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Chart } from 'chart.js';
import { WebSocketService } from './web-socket.service'; // Assume a service to manage WebSocket
@Component({
selector: 'app-live-data-chart',
template: '<canvas id="myChart"></canvas>',
styleUrls: ['./live-data-chart.component.css']
})
export class LiveDataChartComponent implements OnInit, OnDestroy {
chart: any;
dataSubscription: any;
constructor(private webSocketService: WebSocketService) { }
ngOnInit(): void {
this.chart = new Chart('myChart', {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Live Data',
data: [],
borderWidth: 1
}]
}
});
this.dataSubscription = this.webSocketService.getLiveData().subscribe(data => {
if (this.chart.data.labels.length > 50) {
this.chart.data.labels.shift();
this.chart.data.datasets.forEach((dataset) => {
dataset.data.shift();
});
}
this.chart.data.labels.push(data.label);
this.chart.data.datasets.forEach((dataset) => {
dataset.data.push(data.value);
});
this.chart.update();
});
}
ngOnDestroy(): void {
this.dataSubscription.unsubscribe();
}
}
This piece of code sets up an Angular component with OnInit and OnDestroy lifecycle hooks. It imports the services required for creating a live updating chart using Chart.js library. The WebSocketService is assumed to be a service that manages the WebSocket connection. The chart is initialized on component initialization and gets updated with new data via WebSocketService. The component unsubscribes from the data stream on destruction to prevent memory leaks.
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
@Injectable({
providedIn: 'root'
})
export class WebSocketService {
private socket$: WebSocketSubject<any>;
private readonly backendUrl: string = 'ws://your-backend-url/'; // Replace with your WebSocket backend URL
constructor() {
this.socket$ = webSocket(this.backendUrl);
}
public getLiveData(): Observable<any> {
return this.socket$.asObservable();
}
}
This piece of code defines the WebSocketService that is responsible for connecting to a WebSocket server and exposing a method that returns an Observable for the live data stream. The service uses the rxjs/webSocket module to create a WebSocketSubject that manages WebSocket connection and provides an Observable stream.