SignalR Update Chart not working as expected

Viewed 126

Iam using Net Core api and angular, and I have one dashboard here There are some charts. I open this page with two different user. And when I change in database something,from signalr api both changed data and unchanged data are coming like below in console.log. In db I changed 3 to 2 last second element only.

  home.component.ts:2153 -1,1,31.01.2020,-1,2,-1
2 home.component.ts:2153 -1,1,31.01.2020,-1,3,-1
2 home.component.ts:2153 -1,1,31.01.2020,-1,2,-1
  home.component.ts:2153 -1,1,31.01.2020,-1,3,-1
  home.component.ts:2153 -1,1,31.01.2020,-1,2,-1
2 home.component.ts:2153 -1,1,31.01.2020,-1,3,-1
  home.component.ts:2153 -1,1,31.01.2020,-1,2,-1

In core part in controller I call this. It call one method and it returns data

[HttpGet]
[Route("Charts")]
public IActionResult Charts(int refShare, int sicil)
{
    var timerManager = new TimerManeger(() => _hub.Clients.All.SendAsync(refShare.ToString(), new { type = "chart", data= _repo.SharingDashboard(refShare, sicil) }));
    return Ok(new { Message = "Charts Completed" });
}

In angular part

this._hub= new signalR.HubConnectionBuilder().withUrl(Url.url.signalR.getMessages, {
      skipNegotiation: true,
      transport: signalR.HttpTransportType.WebSockets
}).build();
this._hub.start().
    then(()=>console.log("Connection Started")).
    catch(err=>console.log(err));
this._hub.on(this.refShare.toString(),(data)=>{
    this.RealTimeDahboard(data.data)
});
this.startHttpRequest();

When I write console.log in RealTimeDahboard() function above result comes. So my chart is always changing. It happens when I open with two user at the same time. If I open one user, it works normally. What can be the reason ?

Thanks for any help

1 Answers

This provably happens because when your second user connects to the hub and calls your method, it instantiates the new TimerManeger() and so you have 2 instances calling the hub method _hub.Clients.All.SendAsync().

So if for example you will have 10 users, you will receive 10 times the data each timer tick.

What you doing here with signalr is not the right thing to do. When you client connects to the hub, it should not trigger a http method. I would recommend just to add your clients to a chart group, and your timer service send the updated chart data to all clients connected to that group.

I have a GitHub project that also refresh chart data in real time using SignalR and you can see how I approached your similar problem there. You can have a look here.

I have a similar project with charts on GitHub and you can see how it is done.

Related