Let's create a live chat with Socket/Angular/Node.
Tags: node, angular, socket, codenewbie
Published: 2020-06-19 06:31:08

Hello folks,

So as you already know from the title we are going to create a live chat with Socket, Angular, and Node.. and we are not going to connect it with the database as it can be your first project with the socket.

Before starting let's have a look on what's we gonna create,

### Sample Output:-
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/wkdjuud3fr95yygr7idg.png)

Find this project here : <a href="https://github.com/Deep1144/sockettry">Github</a>

<hr>

So, Let's start: 

<b>1. </b>
First let's setup the project :
```bash
mkdir chat
cd chat
ng new client
express server
```
execute the commands given to set up our application first :

after this your folder should look like this :

chat
  |-client
  |-server

<hr>

<b>2. </b>

So, now let's start with creating the basic UI first. 

Replace your index.html with this code:

```html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Client</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

</head>
<body>
  <app-root></app-root>

  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
</html>
```
here we added bootstrap to our project..

And after this :
Go to 
<mark>/client/src/app/app.component.html</mark> and replace the code with the following:

```html
<div class="m-5">
  <h2>Online
  <span class="badge badge-pill badge-light" style="color: greenyellow;">
    2
  </span>
</h2>
<input type="text" class="form-control w-25" placeholder="Enter a message">
<button class="btn btn-light mt-2">
  Send message
</button>

<br><br><br><br>
<h3>Messages</h3>
<ul class="list-group">
  <li class="list-group-item" >item </li>
</ul>
</div>
```


Run this code in the client folder,
```bash
ng serve -o 
```
to see our code in action..
you will see we are done with our basic UI.


<hr>

<b>3. </b>

Let's create a service first..
in client/src/app run:
```bash
ng g s socket
```
and also run to install socket client 

```bash
npm i socket.io-client --save
```

And put the following code in socket.service.ts:
```typescript
import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SocketService {

  socket;
  socket_endpoint = 'http://localhost:3000';


  constructor() {
    this.socket = io(this.socket_endpoint);
  }

  sendMessage(msg){
    this.socket.emit('new-message',msg);
  }

  getMessage(){
    return Observable.create((observer)=>{
      this.socket.on('new-message' , (message)=>{
        observer.next(message);
      })
    })
  }

  getOnUser(){
    return Observable.create((observer)=>{
      this.socket.on('on-user',(count)=>{
        observer.next(count);
      })
    })
  }

}

```




After this Goto ,
<mark>/client/src/app/app.component.ts</mark> 
And place the following code..


```typescript
import { Component ,OnInit} from '@angular/core';
import {SocketService} from './socket.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'client';


  message = '';  //message typed by user
  msgList = []; //list of messages
  userOnLine :Number = 0; //number of online users
  constructor( public socketService:SocketService ){}

  ngOnInit() {
    this.getMessage();
    this.getOnUser();
  }

  getMessage(){
    this.socketService.getMessage().subscribe((message) => {
      console.log(message);
      this.msgList.push(message);
    })
  }

  getOnUser(){
    this.userOnLine = this.socketService.getOnUser().subscribe((res)=>{
      console.log(res + ' user online');
      this.userOnLine = res as Number;
    });
  }

  sendMessage() {
    if(this.message.length == 0)
      return;

    this.socketService.sendMessage(this.message);
    this.message = '';
  }
}

```


Message variables will hold the message typed by the user for this we will use two-way binding.

To use two-way binding let's first import FormModule.
Add the followings in <mark>app.module.ts</mark> file:

```typescript
import { FormsModule } from '@angular/forms';

imports:[
FormsModule
]
```


Now to enable two-way binding let's format the code of app.component.html:

```html
<div class="m-5">

  <h2> Online
    <span class="badge badge-pill badge-light" style="color: green;">
      {{ userOnLine }}
    </span>
  </h2>


  <input type="text" class="form-control w-25" [(ngModel)]="message" placeholder="Enter message">
  <button class="btn btn-light mt-2" (click)="sendMessage()">
    Send Message
  </button>


  <br><br><br><br>
  <h3>Messages</h3>
  <ul class="list-group">
    <li class="list-group-item" *ngFor="let item of msgList">{{ item }}</li>
  </ul>
</div>

```

With this, we are all done with our client-side...
So, let's Do our backend now...


<hr>

<b>4. </b>


First, let's install some dependencies:
Run this command inside server/
```bash
npm install socket.io --save
``` 

then,

In, <mark>server/bin/www</mark> add:

```javascript
const io = require('socket.io')(server);
require('../socket/base')(io);
```

<hr>

<b>5. </b>
Now let's create that base file we imported in the above step : 

create a folder named socket inside the server folder...
And, create a base.js file in that folder.

Server
|- socket
..|- base.js


IN base.js file :

```javascript
var userCount = 0;
module.exports = (io)=>{
    io.on('connect', (socket)=>{
        userCount++;
        
        socket.on('disconnect',()=>{
            userCount--;
            io.emit('on-user',userCount);
        });

        socket.on('new-message',(msg)=>{
            io.emit('new-message',msg);
        });

        io.emit('on-user',userCount);
    });
}
```

paste this code and restart both of your server's


Now let's have a look at our final output....

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hj5whv5cuwq5q8e6uj07.png)

Find this project here : <a href="https://github.com/Deep1144/sockettry">Github</a>

Please give a follow in Github if you liked this article...