You are on page 1of 6

Angular + SignalR

What is SignalR? (.net core)

ASP.NET SignalR is a library for ASP.NET developers that simplifies the process of adding
real-time web functionality to applications.

Real-time web functionality is the ability to have server code push content to connected clients
instantly as it becomes available, rather than having the server wait for a client to request new
data.

Good candidates for SignalR:

o Apps that require high frequency updates from the server.


- gaming
- social networks
- voting
- auction
- maps
- GPS apps
o Dashboards and monitoring apps.
- company dashboards,
- instant sales updates
- travel alerts
o Collaborative apps.
- whiteboard apps and
- team meeting software
o Apps that require notifications.
- social networks,
- email,
- chat,
- games,
- travel alerts
Transports

SignalR supports several techniques for handling real-time communications:

 WebSockets

 Server-Sent Events
 Long Polling

Hubs

SignalR uses hubs to communicate between clients and servers.

A hub is a high-level pipeline that allows a client and server to call methods on each other.
SignalR handles the dispatching across machine boundaries automatically, allowing clients to
call methods on the server and vice versa.

You can pass strongly-typed parameters to methods, which enables model binding.
POC

- Simple public chat application with angular and SignalR

Prerequisites:

 Make sure you have the latest -.NET Core SDK


 Angular CLI
 NodeJS

Angular part:
1) Create a new angular project
In cmd -> ng new AngularSignalR
2) Install SignalR node package

- npm install @aspnet/signalr

3) In your app.component insert the following code:


export class AppComponent implements OnInit {

public hubConnection: HubConnection; // connect to the server


public messages: Message[] = []; // list of messages stored locally
public message: Message; // message to send

ngOnInit() {
this.message = { //initialize model
CreatedDate: null,
CreatedBy: null,
MessageBody: ''

};

const builder = new HubConnectionBuilder();

this.hubConnection = builder
.withUrl('http://localhost:57911/route') // [route] the route where the
clients should connect
.build();

this.hubConnectio // we build and start our connection


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

this.hubConnection.on('ReceiveMessage', (message) => {


// event when received message
this.messages.push(message); // store them to messages
});

send() {
this.message.CreatedDate = new Date(); // function to send message we invoke
sendMessage event from the server
this.hubConnection.invoke('SendMessage', (this.message));
this.message.MessageBody = '';
}
}
class Message {
CreatedBy: string;
MessageBody: string;
CreatedDate: Date;
}

.Net Core part:


1) Create api web project in .NET CORE
2) Make a new hub class that inherits the hub base class and insert the following code:

public class MessageHub : Hub


{
public void SendMessage(Message message) // clients invoke this event
{
Clients.All.SendAsync("ReceiveMessage", message); // sends a message to all
connected clients
}
}

public class Message


{
[JsonProperty("CreatedBy")]
public string CreatedBy { get; set; }

[JsonProperty("MessageBody")]
public string MessageBody { get; set; }

[JsonProperty("CreatedDate")]
public DateTime CreatedDate { get; set; }

}
3) Allow cors for localhost
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});

4)Add route where the clients should connect


app.UseSignalR(routes =>
{
routes.MapHub<MessageHub>("/route"); // clients should connect here
});

Run project and play with it.


You don’t need to install SignalR package for .net core because it is integrated in it

You might also like