Chat App

Are you new to Angular2 and NodeJS? Is Socket.io confusing? Need a clear explanation on these setups? Then here you are at the right place.

In this blog, you will come to know how to create a simple chat application using Angular2, NodeJS and socket.io. Here is providing you the basic configuration and the setup.

PREREQUISITE

Before we jump into the configuration, please make sure the foundation is strong. The required packages, latest version of node and npm.

  • Client referred here will be using Angular2.
  • Server referred here will be using NodeJS.
SERVER CONFIGURATION OF SOCKET.IO

1. Create a node project:

npm init  should create a node project for you.

2. Add express to it:

npm install –save express

3. Setup socket:

Require socket – var io = require(‘socket.io’)(http);

Establish the socket connection

io.on(‘connection’, function(socket){

console.log(‘user connected’);

socket.on(‘disconnect’, function(){

console.log(‘user disconnected’);

});

});

Now your app.js should look like

Sever-app.

4. Add custom message:

Add custom message to which your server will respond in the connection you have established.

custom-message

node app.js should run your application.

 

CLIENT CONFIGURATION OF SOCKET.IO

1. Create an Angular2 project:

You can clone the project from Angular.io (the official website) or generate using Yeoman.

2. Create a Chat service:

We will create a chat service, establish the socket connection and add getter’s and setter’s to it.

Create a app.chatservice.ts file and add this code there.

chatservice

3. Create the UI:

We need a UI to perform the chat right.

Create a file chat.html, and add this code there

chat-ui

4. Create the component:

In your component, add functionality to the sendMessage function.

chat-component

 

5. Wire-up with the Node project:

Create a app.settings.ts file and add this code

chat-setting

 

Now, when you run your client code the application should start running. Get on and move ahead!