Skip to content

Instantly share code, notes, and snippets.

@bartoszgajda55
Last active August 17, 2021 15:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bartoszgajda55/611aeff3c9ad09eeb6b0b8522d1688f1 to your computer and use it in GitHub Desktop.
Save bartoszgajda55/611aeff3c9ad09eeb6b0b8522d1688f1 to your computer and use it in GitHub Desktop.
Using Angular and Chart.js to build real-time charts
<mat-card>
<mat-card-title>Number of RSVPs created</mat-card-title>
<mat-card-subtitle
>Counted number of events created, within every 10 second
window</mat-card-subtitle
>
<mat-card-content>
<canvas
baseChart
width="600"
height="400"
[datasets]="countEventsData"
[chartType]="countEventsChartType"
[labels]="countEventsLabels"
[colors]="countEventsColors"
[options]="countEventsOptions"
></canvas>
</mat-card-content>
</mat-card>
import { Component, OnInit, OnDestroy } from "@angular/core";
import { SseService } from "src/app/services/sse/sse.service";
import { Label, Color } from "ng2-charts";
import { ChartDataSets, ChartOptions } from "chart.js";
import { CountEvents } from "src/app/model/CountEvents.model";
import { Subscription } from "rxjs";
@Component({
selector: "app-count-events",
templateUrl: "./count-events.component.html",
styleUrls: ["./count-events.component.scss"]
})
export class CountEventsComponent implements OnInit, OnDestroy {
private countEventsSubscription$: Subscription;
private eventsOnChartLimit = 20;
countEventsChartType = "line";
countEventsData: ChartDataSets[] = [
{ data: [], label: "Number of Events", fill: false }
];
countEventsLabels: Label[] = [];
countEventsColors: Color[] = [
{
borderColor: "#039BE5",
pointBackgroundColor: "#039BE5"
}
];
countEventsOptions: ChartOptions = {
animation: {
duration: 0
}
};
constructor(private sseService: SseService) {}
ngOnInit() {
this.countEventsSubscription$ = this.sseService
.getServerSentEvent("http://localhost:8082/count-events")
.subscribe(event => {
let data = JSON.parse(event.data);
this.pushEventToChartData(data);
});
}
private pushEventToChartData(event: CountEvents): void {
if (this.isChartDataFull(this.countEventsData, 20)) {
this.removeLastElementFromChartDataAndLabel();
}
this.countEventsData[0].data.push(event.count);
this.countEventsLabels.push(
this.getLabel(event)
);
}
private getLabel(event: CountEvents): string {
return `${event.window}`;
}
private removeLastElementFromChartDataAndLabel(): void {
this.countEventsData[0].data = this.countEventsData[0].data.slice(1);
this.countEventsLabels = this.countEventsLabels.slice(1);
}
private isChartDataFull(chartData: ChartDataSets[], limit: number): boolean {
return chartData[0].data.length >= limit;
}
ngOnDestroy() {
this.countEventsSubscription$.unsubscribe();
}
}
import { Injectable, NgZone } from "@angular/core";
import { Observable } from "rxjs";
@Injectable({
providedIn: "root"
})
export class SseService {
constructor(private _zone: NgZone) {}
getServerSentEvent(url: string): Observable<any> {
return Observable.create(observer => {
const eventSource = this.getEventSource(url);
eventSource.onmessage = event => {
this._zone.run(() => {
observer.next(event);
});
};
eventSource.onerror = error => {
this._zone.run(() => {
observer.error(error);
});
};
});
}
private getEventSource(url: string): EventSource {
return new EventSource(url);
}
}
@huipingli2009
Copy link

Where is your src/app/model/CountEvents.model? Can you share this model? Thanks.

@bartoszgajda55
Copy link
Author

Where is your src/app/model/CountEvents.model? Can you share this model? Thanks.

Sure, you can find the snipper below :)

export interface CountEvents {
  _id: string;
  count: number;
  window: {
    start: string;
    end: string;
  };
}

@ylaplace
Copy link

good Morning how can i make a spring boot controller please

@rajdwi22
Copy link

Hi,
I am new to Angular and really liked this concept.
I am not able to find the entre source code or maybe i am not able to setup.
Please can you share the project.
Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment