In this article, we will see how we can create real time clock, using SignalR, Angular 2 and integrate Angular 2 app inside ASP.NET in addition to viewing its results.
Before proceeding to the step by step process of creating a real time clock, it’s better to understand a few important terms and concepts.
What is the meaning of real time communication?
Real time communication (RTC) is a term, which means a communication which does not have delays, as the clients connect to each other through the Server when any client sends a message as soon as the Server receives it it pushes it towards another connected or all the connected clients without any delay. Like Instant Messaging Services, we use popular Services like WhatsApp, IMO and Facebook Messenger.
It uses peer-to-peer connection with minimum latency, RTC data and messages are not stored between the transmissions.
I think, it’s enough to have information on real time communication, if you are willing to deep dive, you can check out the available content on the Web.
Now, we will discuss it.
What is ASP.NET SignalR?
It is an ASP.NET library which adds real time functionality to the Web apps. As we already discussed, in real time communication, the Server receives the data without storing it and pushes it towards the connected clients.
SignalR provides a simple API for generating Server to client Remote Procedure Calls (RPC) that hits with JavaScript functions on the client from the Server side or the same. It is reciprocal from the client to the Server, as it supports bi-directional communication.
SignalR contains built in rich mechanisms for the management of connections, and methods to connect, disconnect or reconnect are available to override, grouping, and authorization.
And the last but not the least technology, which we use to create an app, is Angular 2.
What is Angular 2?
Angular 2 is a rich UI Framework to build mobile and Web applications. It is built using JavaScript. It has many enhancements over its first version, Angular 1. It is recreated and now it is better to develop applications with Angular 2, as it has an extended set of features mentioned below.
- Cross Browser and Cross Platform compatibility.
- Two way data binding.
- Enhanced routing support.
- Modular structure to manage your code.
- Excellent community support.
- High speed and performance
- Fully productive tools to fast pace your work
- Unit testing
This is a brief introduction of all the things we can create with the web app.
So let’s start to build the app step by step.
Step 1
Go to File - New - Project and select ASP.NET Web Application. Afterwards, name the project and the destination. Press OK.
After pressing OK Button it will open new window to select the template of the new project.
In our case, we are using an empty template with MVC check box checked.
Now, press OK button again to create the project.
We have successfully created our Web Application.
Step 2
Now, we will first install SignalR to the created app.
For this, we would right click the project and select Manage NuGet Packages.
NuGet Package Manager Window opens, search SignalR, press Install button to install the packages.
Now, review the changes. A window opens and these changes are reflected on your solution after installing it.
Press OK button to continue.
After this License Acceptance Window opens, click I accept to accept the license, otherwise press I Decline.
As this is the final step towards installing SignalR through NuGet Package Manger and it can install all the dependencies and the Scripts needed for the project. It opens the Project folder in which the change has occurred.
You can verify if the package is installed or not by verifying the tick mark on the package which you installed in the NuGet Package Manager Window.
Step 3
Download and install NodeJS for Windows.
Go to https://nodejs.org/en/ and click on the recommended version to be installed for Windows.
After downloading, install Microsoft installer file and follow the steps to install in your local machine.
To check if it has successfully installed on your local machine, open Command Prompt Window and Type node –v and hit enter. If it returns the node version, as shown in the image, it has been successfully installed.
Also, verify NPM is installed by typing the command npm –v.
Step 4
Add OWIN Startup class to the project by adding New Item to the root of the project.
After the file is created, add the code given below to the file inside Configuration method.
- app.MapSignalR();
Step 5
Add SignalR Hub Class to the Project. The better approach is to make a folder with the name of hubs and add Hub Class inside it.
We first create the folder, namely Hubs, and create a Hub Class by right clicking on the folder. Select Add è SignalR Hub Class, name it and it will add hub class to the folder.
I have created Hub class with the name of Clock. By default, it will be created with Hello method.
Copy and paste the method given below to follow this tutorial.
- public void GetRealTime() {
- Clients.Caller.setRealTime(DateTime.Now.ToString("h:mm:ss tt"));
- }
Now, let’s elaborate on this method. As you can see GetRealTime is a hub method and it is a Server side method. From client, we hit this Server side event and on the result, it makes a remote procedure call and sends the response back to the client by calling Clients.Caller.setRealTime method, which is then used in the client side to accept the response and show to the client.
Caller means the calling client, which is connected to the hub.
setRealTime function is used in the client end to broadcast and show the response.
Step 6
Now, we will move to setup the Angular 2 environment for your project.
If you want to quick start your project, you can use the ready made available project of Angular2 from official GitHub account of Angular2 and clone the project to do a quick start.
I have enlisted the steps below to setup your local development environment.
- Make sure that you have installed node and NPM. Node is for the client side Applications and build tools and NPM Package Manager installs JavaScript libraries.
- Create Angular 2 folder on the root of your project and then app folder, where we place only Angular2 code and in Angular2 folder, we place the configuration and other files are required at the root.
- Create the Configuration files.
- First, create the tsconfig.json file. For this, press Ctrl + Shift + A or right click Angular 2 folder and select Add New Item from context menu. A new Window appears, select JSON file, name it tsconfig.json and press Add to create the file. The basic purpose of this file is to set the environment for TypeScript compilation configuration. Through this file, all TypeScript files transpiles to Javascript. Add the code given below to the file.
- {
- "compilerOptions": {
- "target": "es5",
- "module": "system",
- "moduleResolution": "node",
- "sourceMap": true,
- "emitDecoratorMetadata": true,
- "experimentalDecorators": true,
- "removeComments": false,
- "noImplicitAny": false
- },
- "exclude": ["node_modules", "typings/main", "typings/main.d.ts"]
- }
- Now, create the file through the procedure given above, namely typings.json, which can identity the TypeScript definition’s file in your Angular Application. There are three types of files defined in file. A) core-js b) jasmine and c) node. Copy the code given below to the file.
- {
- "globalDependencies": {
- "core-js": "registry:dt/core-js#0.0.0+20160602141332",
- "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
- "node": "registry:dt/node#6.0.0+20160621231320"
- }
- }
- Now, create package.json file. This file contains the packages required by our app. The packages are installed and maintained, using Node Package Manager. Copy the code given below to the file.
- {
- "name": "angular2realtimeclock",
- "version": "1.0.0",
- "scripts": {
- "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",
- "tsc": "tsc",
- "tsc:w": "tsc -w",
- "lite": "lite-server",
- "typings": "typings",
- "postinstall": "typings install"
- },
- "license": "ISC",
- "dependencies": {
- "angular2": "2.0.0-beta.7",
- "systemjs": "0.19.22",
- "es6-promise": "^3.0.2",
- "es6-shim": "^0.33.3",
- "reflect-metadata": "0.1.2",
- "rxjs": "5.0.0-beta.2",
- "zone.js": "0.5.15"
- },
- "devDependencies": {
- "concurrently": "^2.0.0",
- "lite-server": "^2.1.0",
- "typescript": "^1.7.5",
- "typings": "^0.6.8"
- }
- }


Amit KhatriPosted Dec 25, 2020, 5:13 AM
Hello Muhammad, nice article. I am using this approach with Angular 10 and its working fine with the static server connection URL ($.hubConnection(CONFIGURATION.baseUrls.server). I want to use dynamic URL that would come from a API response that needs to be passed in the $hubConnection. I tried some code given below setupConnection(serverBaseUrl) { // create hub connection this.connection = $.hubConnection(`${serverBaseUrl}`); // create new proxy as name already given in top this.proxy = this.connection.createHubProxy(this.proxyName); // call the connecion start method to start the connection to send and receive events. this.startConnection(); // register on server events this.registerOnServerEvents(); } But using this approach proxy.on('setRealTime', (data) => { // Here it is not listening data. console.log('received in SignalRService: ' + JSON.stringify(data)); this.messageReceived.emit(data); }); Any help ? Thank you in advance.
Mounika ChundiPosted Jan 31, 2018, 1:56 AM
Hi Muhameed,Thanks for nice article .I am having same problem which most of the users commented here. I am trying to run angular app independently from service. I am getting error 'Cannot read property 'hubConnection' of undefined' even though included jquery-signal references in angular app.Can you please assist me to solve this problem in my application
Vijendra GathlePosted Jan 30, 2018, 1:43 AM
Hi Muhammad, I used your code in angular 4 with vs 2017 i got the error (SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.).
Mohamed FouadPosted Oct 17, 2017, 6:30 AM
Hi Muhameed, I worked on your example and worked very well, but I want the server to automatically send the the time without invoking the server each second, do you have any idea how to do that !? , thanks
nachoPosted Sep 15, 2017, 11:28 AM
Thanks for sharing. I'm having some trouble with this line this.connection = $.hubConnection(CONFIGURATION.baseUrls.server); I get the error "Uncaught (in promise): TypeError: Cannot read property 'hubConnection' of undefined" Any tip what could be the problem?
Miguel MartínezPosted Jun 22, 2017, 7:26 AM
Thanks for sharing. I'm having some problems trying to follow this tutorial. This is one of my first angular 2 applications. I couldn't find two things inside this tutorial and I'm getting errors abouting. 1) routing file 2) systemjs .config.js. I was wondering if you could assist me with these files to be able to finish the tutorial
Vivek KumarPosted Mar 21, 2017, 7:25 AM
Nice article. Thanks for sharing
Thiruppathi RPosted Feb 26, 2017, 11:51 PM
Nice Article. Thanks for sharing....
phakawan wongpetananPosted Feb 25, 2017, 12:34 PM
This article really help me.
Vignesh ManiPosted Feb 24, 2017, 5:25 PM
Nice article. Thanks for sharing
Ehsan SajjadPosted Feb 24, 2017, 10:05 AM
Cool Stuff, keep them coming @Aqib :)
Vishal PrajapatiPosted Feb 23, 2017, 10:13 PM
Thanks for sharing...
Humayun Kabir MamunPosted Feb 23, 2017, 6:53 AM
Thanks for this nice article...
Syed ShanuPosted Feb 23, 2017, 1:56 AM
Simple and useful post Muhammad Aqib Shehzad