I have a Blazor server app where I have used chart.js library for my chart with JSInterop. In the line chart I am showing 20 measuring values The chart is working fine when all the 20 values are present and I open the chart. The chart draws the curve for 20 values.
But I want to use that chart as live chart. That means when every second a new data value comes into the data array, I want to update the chart. How is this possible?
Here my code:
My razor page where the chart is
@page "/wmi_performance2"
@inject TagService TagService
@using System.IO
@inject IJSRuntime JSRuntime
<Chart Id="bar1" Type="@Chart.ChartType.Bar"
Data="@CPU_Load_array"
Labels="@Measuring_points_array">
</Chart>
My Chart.razor in the Shared/Components folder
@using System.IO
@inject IJSRuntime JSRuntime
@using Microsoft.JSInterop;
@inject IJSRuntime jsInvoker
<canvas id="@Id"></canvas>
@code {
public enum ChartType
{
Pie,
Bar
}
[Parameter]
public string Id { get; set; }
[Parameter]
public ChartType Type { get; set; }
[Parameter]
public string[] Data { get; set; }
[Parameter]
public string[] BackgroundColor { get; set; }
[Parameter]
public string[] Labels { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender)
{
// Here we create an anonymous type with all the options
// that need to be sent to Chart.js
try{
var config = new
{
Type = Type.ToString().ToLower(),
Options = new
{
Responsive = true,
Scales = new
{
YAxes = new[]
{
new { Ticks = new {
BeginAtZero=true
} }
}
}
},
Data = new
{
Datasets = new[]
{
new { Data = Data, BackgroundColor = BackgroundColor}
},
Labels = Labels
}
};
await JSRuntime.InvokeVoidAsync("setup", Id, config);
}
catch(Exception e)
{
using (StreamWriter sw = File.AppendText((Pages.CommonClass.error_path)))
{
sw.WriteLine("Chart.JS Error: " + e + Environment.NewLine);
}
}
}
}
My chart.js under wwwroot
window.setup = (id, config) => {
var ctx = document.getElementById(id).getContext('2d');
new Chart(ctx, config);
}