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

Shashank Tiwari
9 min readSep 5, 2018

--

This post has been published first on codershood.info.

The complete source code is available on Github.

This is the second part of the Building Real time private chatting app using Angular. In this part, you will implement below-listed features in your application,

  1. Registration.
  2. Checking uniqueness of the username before registration.
  3. Login.
  4. Checking the Session of a user (when the user navigates to the home page).

In the First part of the Series, we did the setup of Angular and Nodejs application. Since I have created boilerplates for Both Angular and Nodejs, therefore you don’t have to do the monotonous work for your self.

I assume you have cloned or downloaded the Angular boilerplate and Nodejs boilerplate. I highly recommend you to clone/download, If you haven’t cloned/downloaded these boilerplates already.

If you use Boilerplates, your application will be less prone to mistakes. Since we are using them to make HTTP calls and listen to the real-time event of the socket event, hence I won’t share and explain the source code of services.

Okay, now install and run both the boilerplates that you have for Angular application and Nodejs server. I hope till this point, you are with me. And somehow if you are having any trouble let me know.

Implementing Registration Feature:

Let’s start by implementing Registration feature. I don’t think I have much to talk about the importance of registration feature. First, we will write the client side code. Later we will write node APIs and all code related to it.

=> So the first step is writing MarkUp, so open the auth.component.html and write down the below code.

auth.component.html:

Explanation:

  1. The first thing to notice is here is we are using ng-bootstrap.
  2. If you are not familiar with it, I would recommend you to check it and use it.
  3. After that, we have a typical Angular Form and some message that would be visible when validation fails.
  4. Nothing difficult to understand here also the picture will be more clear once you will write the code inside the component class.

To make your markup work, you will have to write some code inside your component class. Open the auth.component.ts and write down the below code.

=> In the below code, we will create an instance of FormGroup. You will use this FormGroup instance in your registration form.

=> The application will redirect the user to the Home Page as soon as the user finishes the registration process.

auth.component.ts:

Explanation:

  1. Starting with imports, First, we will import services and Interfaces. In the first part of this series, we had discussed the scope of each file, So you must know why we are usingChatService and FormService.
  2. The setTabPosition is used for aligning the tabs into the center.
  3. Inside the constructor function, you will call createRegistrationForm(), and assign the value of it to theregistrationFormproperty of the component class.
  4. Then in registration method, you will call a register() method of ChatService class by passing the values of the registrationForm.
  5. After receiving the response from the server, You have to do two things based on the response received from the server.
  6. First, after successful registration, you will store the userId into Local Storage. Then you will redirect the user to the Home page.
  7. Second, you will display some alert message if anything goes wrong.

Forgive me for showing ugly messages. For the sake of simplicity, I have used the usual alerts, instead of fancy POPUPs.

To complete the registration process you will have to write code in Nodejs as well. Basically, writing Nodejs code will piece of a cake for you, because you don’t have much to write. Let’s get to it, Open the routes.js and add the below the route.

routes.js:

=> After that, you have to write few lines of code inside theregisterRouteHandler(), just to handle the request/response and call the method which just inserts the data into Database.

=> Add the below code, inside the route.handler.js file. TheregisterRouteHandler()will take care of the /register route.

route.handler.js:

Explanation:

  1. In the above code, you will first check the validation. If anything wrong with that, we will send the proper error code with an Error message.
  2. Then we will generate the Password Hash for user entered password.
  3. And the end if everything is valid or in more precise words if the request is valid than you will Register a user by callingregisterUser().
  4. TheregisterUser()is defined inside the query-handler.js.

Open the query-handler.js file and write down the below code. As you have figured it by now, You will just have to insert the records in MongoDB in the below code.

query-handler.js:

Explanation:

  1. In the above code, First thing you will do is return promise. By returning promise you can save yourself from callback hell, and later you can apply Async/Await on this function.
  2. After that, you will connect the MongoDB database and insert the record into the database.
  3. And that’s it. You have created a new user.

Checking for a unique username

It is very important that before registration, you check the uniqueness of username. It’s obvious that you can’t have two users with the same username.

First thing first, let’s add the Markup in authentication.component.html.

=> Here you don’t have much to write, just an indicator that shows the particular username is taken.

=> In the below Markup, we have used the *ngIf directive to hide and show the Message by using the isuserNameAvailable property of AuthenticationComponent class.

authentication.component.html:

The above markup will hide/show only if you write something in your component class file.

First of all, add the below property in your AuthenticationComponent class,

After that add the below in AuthenticationComponent class, The below code will check the username uniqueness by Making an HTTP request to your Nodejs server. Open the authentication.component.ts and add the below code.

authentication.component.ts:

Explanation:

Add this method inAuthComponent class, now let’s break this method from the top to bottom and understand what it does.

  1. Using valueChanges you can subscribe to any value of the Form. Whenever a value changes in the field of a form you will get to know the new value.
  2. debounceTime will add an extra delay of 800ms. Am sure you don’t want to make HTTP calls as soon as the user starts typing Right?
  3. distinctUntilChanged will make your subscriber listen only for distinct values.
  4. And at the end, if everything goes well and good, then you will call ChatService to check the uniqueness of the user.
  5. Based on the response, the Angular will hide/show the username uniqueness indicator.

This is not complete yet, you still have to code for your Nodejs part. Writing Nodejs routes and its helper will be the same as it was in the last section, In fact, it’s going to be identical for Nodejs routes. So first as usual open the routes.js and add the below the route.

routes.js:

Now our express route is added, let’s write a method to handle that request in the route-handler.jsfile. Open that file and add the below code,

route-handler.js:

If you notice we have calleduserNameCheck() method to check the user count of same usernames. This method will basically check the counts of the given username and returns that count to the callee.

Open the query-handler.js and add the below code, in the below code you just a run a MongoDB query and return the response to caller method.

query-handler.js:

Now, this completes your Checking for a unique username features. Congrats, you have added one more feature to your application.

Implementing Login Feature:

Implementation of Login feature is going to pretty easy and almost identical to above-implemented features. First, we will start with Markup, then component and in the end, we will write some NodeJs just like we did in the last two sections.

=> The below markup will render the Login form, which will have two fields username and password.

=> Open the authentication.component.html and add the below inside the Login Tab.

authentication.component.html:

To make our Login Form fully functional, you will have to write some TypeScript in your Component class. First thing first, you need to initialize the Login Form by calling FormService. Form service will basically give you an instance of the Login form.

Add the below property to the AuthenticationComponent class.

authentication.component.ts:

As of now, loginForm is empty having a type as FromGroup. To give the instance of form field you have to call FormService.

Add the below line to the constructor function.

authentication.component.ts:

Our Angular Form is ready now, Only thing is left to handle a Form submission. We will write a login() method in AuthenticationComponent class to do that.

Open the authentication.component.ts and write down the below code.

authentication.component.ts:

Let’s write the Nodejs part, Here we will do three things First we will add the route. Second, we will add a method to handle the request/response of the route and at the end method to perform the Login.

So let’s just add the route, open the routes.js. and add the below route.

routes.js:

The/loginroute is added to its respective file, now let’s write the method to handle the response to the/loginroute. Open the route-handler.js and add the below code,

route-handler.js:

Explanation:

  1. There is a lot of things going on here, First, we will do the validation if everything goes fine, then we will actually fetch the result from the database and verify it with the data sent from the Angular application.
  2. After validation and stuff, we will fetch the record of the user by using his/her username.
  3. If you get a result from the database using the username, then go ahead compare the password of a user by usingcompareHash() method.
  4. After comparing the password, based on the result you will make the status of user online.

Checking User’s Session

It is very critical to check session of the user before allowing the users to chat and read messages. To check the session of the user, we will make an HTTP call.

Whenever a user visits the home page of the application we will check the session. And by the way, we won’t make an HTTP call to check the user’s session. We will setup Angular Gaurd for /home route to do that work for us.

If you are using the boilerplate, you will find a file named as auth-guard.service.ts in the folder /services. I assume that you have prior knowledge Angular Route guard.

So all you have to do is uncomment thecanActivate property in pages-routing.module.ts file and you are done.

pages-routing.module.ts :

Now let’s add the route for session check service in the routes.js file. Here we will check the online status of the user, and based on the online status we will determine the session of that user. So add the below route in the routes.js file.

routes.js:

As always, we have to write method inside the route-handler.js file to handle the response for the /userSessionCheck route. As you can see, in this case, we are calling userSessionCheckRouteHandler() to handle the response for the /userSessionCheck.

Open the route-handler.js and add the below code,

route-handler.js :

Explanation:

  1. In the above code, First, we will check for the userId validation. If the validation fails, we will send the user not found a response.
  2. If validation passes, then we will check the online status of the user in Database by using userId.
  3. And depending on the online status we will send the response to Angular Application.

Now to check the online status in Database you will have to writeuserSessionCheck() method in QueryHandler class. This method will basically check the online status by executing a MongoDB Query.

Open the query-handler.js file and add the below method,

query-handler.js:

And I assume above code needs no explanation, since you are just executing a MongoDB query and returning a Promise.

That’s it.

Conclusion

Now let’s conclude this part by recapping what we did in this part.

  1. We downloaded theAngular boilerplateandNodejs boilerplateand using these created our application.
  2. We implemented a Registration feature.
  3. We implemented a feature to check uniqueness of the username before registration.
  4. We added Login functionality in our application.
  5. At the end we added a feature to check the session of a User.

In next part of the series, we will connect our Angular application to the socket and implement the Realtime chat list for the application.

So stay tuned it’s going to more interesting.

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.

--

--