Updated February 14, 2023
Introduction to SignalR Angular
SignalR Angular is an Open-Source Library that is used to make things easier, like it is the process of including the Real-Time functionality of the Web to the applications. It has the capability of having server code to move forward the content to the associated clients right away as it becomes accessible than having the server, which is to remain for the client to demand the new data. SignalR app can measure thousands of customers by using third-party and built-in providers.
Ā
Ā
What is SignalR Angular?
SignalR Angular is a powerful technique that allows WebSocket Connections between customers. SignalR helps out by offering real-time web functionality to the applications. It describes the server moving the data to any of the associated customers so that the data is offered in real-time and so on. SignalR supports the Server Push functionality in which the server code calls the client code in the browser by using the RPC (Remote Procedure Calls) than the request response model.
SignalR Angular Real-Time Chart
SignalR is the library that offers the real-time functionalities of the web to the applications. It defines that the server pushed the data. Here let us see the usage of SignalR with the .NET Core and the Angular, to simulate the real-time data flow by using the Timer class in the .NET Core and the use of data.
In this approach, we are using one-way communication (server to client) and adding extra feature like showing two-way communication (client server-client).
ConfigurationĀ Data
In this to build both projects of Angular and the .NET Core, to name them as RealTimeCharts.Client and RealTimeCharts.Server respectively. For the core project, we select the Web API project as empty, and on the Angular Side, we develop the Angular Project with no routing developed and apply the styles of CSS.
Then to create the project which switches the Server-Side Project and to set up the initial configuration, open the LaunchSettings.json file and alter it as shown below.
As soon as projects are created, we are going to switch to the server-side project and set up a basic configuration. Just alter the code of the file launchSettings.json.
Then in Server Side, our project will execute on the Localhost:5001, and on the Client-Side, it will execute on the Localhost:4200 to establish the communication between the two, and we are required to allow it. Let’s open the class coding and make it alter as shown below.
Make a note of it like we are not using the AllowAnyOrigin() method, which allows the cors from the origin but explicitly say the origin to enable WithOrigins of localhost. We have to follow this because it is considered an insecure CORS configuration. To make a call on the UseCors method before calling the method UseAuthorization. It is for the configuration.
Next, go to the Angular Project and install the SignalR on the library as follows.
For the regards of client-side install the above process.
npm install @microsoft/signalr ā save.
Then go to the server side and build the folder Models. In this, we create the class ChartModel and alter it as follows.
Code:
publicĀ classĀ ChartModel
{
publicĀ List<int> Data { get; set; }
publicĀ string? Label { get; set; }
publicĀ string? BackgroundColor { get; set; }
publicĀ ChartModel()
{
Data = newĀ List<int>();
}
}
It is expected by the Angular Charts library that’s installed so the Model properties are Label and Data. Next, create new folder HubConfig, and inside create new class ChartHub.
Code:
public class ChartHub: Hub
{
}
The class of ChartHub is derived from Hub Class which is a base class for SignalR hub. We need this because Hub is an advanced pipeline that enables the communication between the server and client to make a call of every method. So Hub is the communication foundation between the client and the server while using SignalR. We have to complete the SignalR configuration so let’s again alter the program as follows.
Code:
builder.Services.AddSignalR();
...
app.MapControllers();
app.MapHub<ChartHub>("/chart");
Here we are including the SignalR to IService collection by using the AddSignalR method, and we are including the SignalR to the request pipeline by pointing to the ChartHub with the chart path.
At last, it is available as follows:
Connecting Microsoft in SignalR Angular
SignalR is the approach of Microsoft that offers real-time communication between the server and the client through WebSockets. We can able to see by it was a high-frequency application like gaming, chat applications, and any real-time updates.
By using SignalR, we can connect the Clients of the Web to transmit and get messages.
Let’s see the following diagram for the basic setup as follows:
Observe the connection process over here as follows:
- Initially, the client makes a call to negotiate the function to set up the WebSocket Connection between the SignalR Service and the client.
- SignalR Service combines and builds the connections by the second function, which the web client listens to it.
- WebClient transmits the messages through the messages function, which is propagated to other WebClients connected to SignalR.
Just connect the Angular Application to create the service, which encloses the package of aspnet/ signalr as follows.
Code:
export class SignalRService {
private readonly _http: HttpClient;
// private readonly _baseUrl: string = "http://localhost:7071/api/";
private readonly _baseUrl: string = environment.azureConnection;
private hubConnection: HubConnection;
messages: Subject<string> = new Subject();
constructor(http: HttpClient) {
this._http = http;
}
private getConnectionInfo(): Observable<SignalRConnectionInfo> {
let requestUrl = `${this._baseUrl}negotiate`;
return this._http.get<SignalRConnectionInfo>(requestUrl);
}
init() {
this.getConnectionInfo().subscribe((info) => {
let options = {
accessTokenFactory: () => info.accessToken,
};
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(info.url, options)
.configureLogging(signalR.LogLevel.Information)
.build();
this.hubConnection.start().catch((err) => console.error(err.toString()));
this.hubConnection.on("notify", (data: any) => {
this.messages.next(data);
});
});
}
Once the service initializes, it refers to the SignalR endpoint, which is exposed from the SignalR service and negotiates the handshake. Then Angular has the ability to emit the details to receive from notify event from SignalR.
Code:
send(message: string): Observable<void> {
console.log("called2");
let requestUrl = `${this._baseUrl}messages`;
return this._http.post(requestUrl, message).pipe(map((result: any) => {}));
}
receieve(message: Message): Message[] {
// read in from local strorage
const messages = this.load();
messages.unshift(message);
localStorage.setItem("messages", JSON.stringify(messages));
return messages;
}
load(): Message[] {
const messagesLocal = localStorage.getItem("messages");
let messagesResponse = [];
if (messagesLocal !== null) {
messagesResponse = JSON.parse(messagesLocal);
}
return messagesResponse;
}
clear(): Observable<void> {
const messagesLocal = localStorage.getItem("messages");
let messagesResponse = [];
if (messagesLocal !== null) {
localStorage.setItem("messages", JSON.stringify(messagesResponse));
}
return of(null);
}
The real components in the application of Angular, which operate the function in chat, have created the reference to the SignalR service and handle the events which come in from the stream consequently.
Code:
this.signalRService.messages.subscribe((message) => {
// create message
const result = message.split("|");
const sendMessage = new Message();
sendMessage.sender = result[0];
sendMessage.body = result[1];
// this.messages.unshift(sendMessage);
this.store.dispatch(
MessagesActions.messageRecieved({ message: sendMessage })
);
});
Conclusion
This article has explained the services of SignalR and Angular. It is a highly improved service in which we can simply integrate the front-end applications.
Recommended Articles
This is a guide to SignalR Angular. Here we discuss the introduction, SignalR angular real-time chart, and configuration data. You can also look at the following articles to learn more –