I will tell you how to Create a real-time private chat app using Angular and NodeJs — Part 2

Shashank Tiwari
10 min readSep 1, 2018

--

This post has been published first on codershood.info.

The complete source code is available on Github.

As the above title reads, we will implement a Real time private chatting app using Angular (Latest) and Nodejs. Now one might ask why on God’s green earth another chat application? Well, In my defense I would like to say,

This is not just another group chat application. It’s a chat application where you will learn much more than just broadcasting socket event. And I assure you, even if you are new in Angular, This application will be a piece of cake for you.

Not convinced yet?

No problem, let’s talk about a few more features. As the title reads Realtime Private chat, Here you will get to know how you can implement real-time private chat between users those who are online. It’s better, I list down all these features instead of writing a paragraph.

  1. First Thing first, you will implement a Login and Registration in your application.
  2. After a Successful Login/Registration, User will be redirected to the Home Page. This Hompage will be protected by none other than Angular Route Guard.
  3. Here You will implement a Realtime chat list, why Realtime because chat list will update automaticallywhen any new user comes online or any existing user goes offline.
  4. On the Home Page, User can initiate a conversation with any other online user. Also, the user can read their old conversation.
  5. Once you are done talking, Then you can use Logout button to go offline.

Also read, Real-Time private chatting app using AngularJs

Let’s take a look at the final outcome of this application, Before going any further.

Login And Registration Page
Chat Page with chat list

So we will implement all the above-listed features in the series of Fours articles. As this article seems little spacious, hence I have divided it into 4 parts. Each part of this article covers a unique part in building the Real Time private chatting app.

First part: Covers the prerequisites, Configuration of Angular application along with Angular routes and Nodejs server setup.

Second part: In this part, you will implement Login and Registration. With that, you will implement a feature to check the uniqueness of the username before registration and the session of a user (when the user navigates to the home page).

Third part: Here you will implement a Realtime Chat list.

Fourth part: In the last part, you will implement chat feature, where the user actually can chat with each other.

Before we start, I want to confess that this series is going to be long, so bear with me and you might also want to go grab a Coffee, Beer or even Water will do; whatever works for you.
So let’s first start with prerequisites.

Prerequisites

Before you start reading this article, I want you to have some knowledge of Angular, Nodejs and MongoDB. Since we are going to use these stacks to implement our application hence you must know the basics.

I assume, that you are familiar with the below-listed topics. Supposing you are not familiar with the concepts listed below, Don’t worry, have a look at below articles and then come back again.

  1. Highlight selected row in Angular 2
  2. Angular 2 CRUD application using Nodejs

Creating a new Angular project

Let’s use Angular CLI to setup our application. If you don’t have Angular CLI installed on your machine run the below command to install it globally.
npm install -g angular-cli
After Angular CLI installation, to create a new Angular project Run below command. This command will create all the necessary files, download all the required external dependencies and do all of the setup work for us.

ng new AppName –routing

Project structure and Folders

In my opinion, it is very important that you understand what folders and files you will create to in this application. You can see all the folders and files in the below image.

The above Image is snapshot /app folder with few folders and files inside it. We have created a few folders, let’s understand the motive of each file and folder.

1./classes:In this folder, you put those files which can be used anywhere in your application. For example, Common classes and methods or it can be anything just a regular program.
In our case, we have custom Angular validators. We will use these validators in our Angular Forms.

2./interfaces: I bet you are familiar with this word. We will see all the interfaces down the road when we will create them.

3./modules: This folder consists of general modules. You can use these modules in any other module of our application. For example, Material Modules, Angular Form Modules, and Any other UI related Module.

4. /pages: You will create all the pages inside this folder. In this application, we have only two pages with a few components inside them.
Though the name of each Angular component is comprehensible. But still, I will list down each component along with its usage for the sake of our conscience.

  1. Authentication Component: We will use it for Login and Registration.
  2. Chat-list Component: As the name suggests, to display the real-time Chatlist.
  3. Conversation Component: This component is used to display messages.
  4. Home Component: This will be the host component of Chatlist and conversation component.

5. /services: This application has total 5 services. We will consume these services in our application and the name of the services are screaming their agenda.

  1. Auth-gaurd Service: Your Angular Route guard will use this service before redirecting to you anywhere.
  2. Data Service: To send data to each component we will use this service.
  3. Form Service: This service will help in building the forms in our component.
  4. Chat Service: This service will hold all your HTTP request.
  5. Socket Service: As the name suggests, In this service, we will emit and subscribe to socket.io events.

Angular and it’s Modules

We all are aware that the Angular is Modular. So why don’t we use this excellent feature of it? Well if you ask me, I would suggest you must. In this application, we will interconnect our all components and services by using Angular modules only.
This way your application will become more simple and modular, as well as your application, will perform much better.

=> Angular by default comes with theapp.module.ts file, which is a top-level module, So open the app.module.ts file and write down the below code into it. In the below code,

=> The important thing is to notice only the import array. In the import array, you will add only two modules First is AppRoutingModule and second will be ServicesModule that’s it.

app.module.ts:

As we discussed above, you will import all the services into this services.module.tsfile.

Which means whenever you create new service just import that service into Services Module and add it into providers array of Services module and you are done.

Open services.module.ts file and write some code into it.

services.module.ts:

Application Routing and Lazy Loading

In this section, we will configure our application’s routing. Since this application is fully modular, hence the application’s routing is divided into several parts.

=> When this application loads in the browser, we will redirect the user to/pages/authenticationroute. This route will display the authentication page.

=>Now theapp-routing.module.tsfile and write down the below code,

app-routing.module.ts:

As soon as the Angular router changes its route to/pages, the Angular application tries to find /authenticationroute inside the pages module.

Why does this happen? The reason is you have registered/pages route with PagesModule inside theapp-routing.module.tsfile.

=> Open thepages-routing.module.tsfile and write down the below code.

=> Here you will register two routes /authenticationand /home.

=> Notice that we have protected our/homeroute with the Angular guard. As of now keep that commented, we will uncomment that later.

pages-routing.module.ts:

As you can see in the above code, we have only two routes, Goes without saying each route points to some module. Here you have two modules, which are listed below,

  1. authentication.module.ts (AuthenticationModule)
  2. home.module.ts (HomeModule)

As of now, You will create two components Authentication and Home. You will create the other two more components inside the /homefolder, down the road.

Here you have to run two CLI commands. The first command to generate module with the routing file.
And the second command you have to run is to generate the component with the same name as the module name. Take a look at below commands,

ng generate module authentication — routing

ng generate module authentication — routing

The above command we will generate theauthentication.module.tsand route fileauthentication-routing.module.tsinside the/authenticationfolder.

ng generate component authentication

ng generate component authentication

This command we will generate theauthentication component inside the/authenticationfolder.

Now you have to do the same for the home module as well and after run the command to generate the home component.

If you run the application at this point, you won’t see much on the screen obviously. You can skip all this step and take the clone of this repository and avoid all the work if you are already pro in Angular.

Creating New Nodejs Project and Application Folder structure

Till now you created and completed Angular application setup. As of now, your angular is nothing a but clean slate, and you will write rest of the A B C D in next 3 part of the series.

In this section, you will create Nodejs API boilerplate. For those who don’t know why Nodejs server is obvious to us,

  1. First, you will need a server where you can store and fetch user’s data and messages.
  2. Second, you need to implement real-time messaging for that we need Web socket.
  3. Third, it is the best choice available out there, you don’t have to learn anything at all except Javascript sure!

Okay so let’s go ahead and start the development, but before that let’s take a look at our folder structure of nodejs server.

Nodejs Server project structure

As you can see, There are five Folders in this application; Here you will create Four folders, expect one folder i.e. /node_modules. As of now, our application is not that much big, so I have kept the folder structure very minimal and easy to understand. In case if you want to go big, I would recommend reading the folder structure guide provided by Rising Stack.

To understand the Purpose of each folder, go through the below-listed points.

  1. /config: In this folder total, we have Four files as shown in the above image. In these files, we will cover the application and express related configuration along with the database connection.
  2. /handlers: Here you will create files, which would include MongoDB query execution and Express route handlers. Which we will see down the road.
  3. /utils: You will create files, which are mainly used as sugar in order to fulfill the other operations. In this case password hashing for Login and Registration.
  4. /web: All your Express Routes and Socket Events will go here.

And at the end, we have .env and server.js file, and I believe these files needs no introduction.

Well, You studied and understood the project structure you have. Now let’s create Nodejs project by running below command.

npm init

This command will create a package.json file, by asking about your project. Now let’s take a look at package.json which, I have created.

package.json:

Creating a Nodejs Server

So you are familiar with the folder structure, it’s time to go ahead a create Nodejs server. You will start your Nodejs in the server.js file, as the name of the file represent itself. Open the server.js file and write down the below code.

server.js:

Explanation:

The above code is straightforward, don’t you think! The server starts in three steps, which are listed below.

  1. First, The app starts with by executing constructor method when we create an Object of Server class.
  2. Second, in the appConfig() method you will include all your configurations.
  3. The last step is, you have to include the Routes and Socket Event.

And all this will happen when you will execute aapExecute() method by creating the Object of Server.

Creating a Configurations Files:

This section is all about writing configuration file, So you will basically deal with the files inside /config folder.

Let’s start with express-config.js file, Honestly at this point, you don’t need this file. Though when your application grows, will need to do express configuration. So open the express-config.js file and write down the below code,

express-config.js:

Second and our main configuration file is the app-config.js file, where you will write all your application related configurations, also you will include ExpressConfig file there. Open theapp-config.js and write down the below code.

app-config.js:

Explanation:

  1. Since this application uses .env file to store configurations, you will dotenv module, read more about it here.
  2. Inside the includeConfig() you will basically use bodyparser and activate CORS for the application routes.

Nothing much to do here, let’s move on to next step.

Connecting with database (MongoDB):

Create adb.jsfile under /config folder and write down the below code. Here I am using the mongodb module, though you can use mongo schema and all. Since I don’t want to make this article more complicated so I will leave that to you.

db.js:

Conclusion

So here we are at the end of the first part. Before jumping to the next part of the article, let’s encore all the step one more time.

  1. We created the Angular application, did all required setup, and understood it’s folder structure.
  2. Second, we created a new Nodejs application and did the configuration.
  3. Also, we created Nodejs server and connected our application to the MongoDB.

In the next part, you will implement Login, Registration, and Logout feature along with other required features. I’ll see you in the next part (Coming Soon).

If you have any suggestion, Question or feature request, let me know in the below comment box, I would be happy to help. If you like this article, do spread a word about it and share with others.

--

--