Angular SignalR
Angular SignalR
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.
WebSockets
Server-Sent Events
Long Polling
Hubs
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
Prerequisites:
Angular part:
1) Create a new angular project
In cmd -> ng new AngularSignalR
2) Install SignalR node package
ngOnInit() {
this.message = { //initialize model
CreatedDate: null,
CreatedBy: null,
MessageBody: ''
};
this.hubConnection = builder
.withUrl('http://localhost:57911/route') // [route] the route where the
clients should connect
.build();
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;
}
[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());
});