fbpx Skip to content

Aquent | DEV6

Angular 2 with WebSockets

Written by: Tunji Akinbami
  1. Introduction to WebSockets
  2. Uses of WebSockets 
  3. Code demonstration (GitHub)

WebSockets

Modern applications today are expected to have real-time/on-demand capabilities. Imagine trying to get live scores of your favourite team playing against a rival and the only way to retrieve live feeds is to constantly refresh your browser. This has been the traditional way of web applications; a client sends a request over a HTTP connection and waits for a response to come back. This is also known as a half-duplex connection.

half-duplex_0

With WebSockets, the client and server are able to share data back and forth simultaneously (full duplex) over the same connection. Using our live scores example, with WebSockets the connection is kept alive and you would not need to refresh your browser to get live updates.

full-duplex

In this tutorial, we’re going to discover how to use WebSockets in Angular 2 by making a simple chat application. Using the popular library socket.io, we’re going to create a Node.js server that listens for WebSocket connections and we’ll use the client side to initiate the socket connection.

server.js

import { Observable } from 'rxjs/Observable';

import * as io from 'socket.io-client';

 

export class ChatService {

  private url = 'http://localhost:8080';

  private socket;

 

  sendMessage(message) {

    this.socket.emit('add-message', message);

    console.log("MESSAGE SENT");

  }

 

  getMessages() {

    let observable = new Observable(observer => {

      this.socket = io(this.url);

      this.socket.on('message', (data) => {

        observer.next(data);

      });

      return () => {

        this.socket.disconnect();

      }

    })

    return observable;

  }

}

In the server.js file, we create a simple Express application and a socket object. The server listens for a connection on port 8080 and logs messages to the console whenever a user is connected or disconnected.

chat-service.ts

import { Observable } from 'rxjs/Observable';

import * as io from 'socket.io-client';

 

export class ChatService {

  private url = 'http://localhost:8080';

  private socket;

 

  sendMessage(message) {

    this.socket.emit('add-message', message);

    console.log("MESSAGE SENT");

  }

 

  getMessages() {

    let observable = new Observable(observer => {

      this.socket = io(this.url);

      this.socket.on('message', (data) => {

        observer.next(data);

      });

      return () => {

        this.socket.disconnect();

      }

    })

    return observable;

  }

}

On the client side, we create a chat service to connect to our WebSocket. With the sendMessage method, we emit the custom ‘add-message’ event that is exchanged between the client and server.  Notice the use of the Observable in the getMessages method. This is done so Angular components can subscribe to messages coming from the server over the socket connection. Subscribers to our observable will be notified of new messages by calling observer.next(). To learn more about Observables you can click here.

chat-component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';

import { ChatService }       from './chat.service';

 

@Component({

  selector: 'chat-component',

  templateUrl: 'chat.component.html',

  styles: [`

    .chat {

      margin-top: 100px;

      margin-left: auto;

      margin-right: auto;

      width: 10%;

      font-family: 'Georgia';

      font-size: 200%;

    }

  `],

  providers: [ChatService]

})

export class ChatComponent implements OnInit, OnDestroy {

  messages = [];

  connection;

  message;

 

  constructor(private chatService: ChatService) { }

 

  sendMessage() {

    this.chatService.sendMessage(this.message);

    this.message = '';

  }

 

  ngOnInit() {

    this.connection = this.chatService.getMessages().subscribe(message => {

      this.messages.push(message);

    })

  }

 

  ngOnDestroy() {

    this.connection.unsubscribe();

  }

}

Finally, we create a chat component where the user can interact with the chat-service. The two critical functions implemented here are ngOnInit and ngOnDestroy which are part of the Angular core API. ngOnInit is used to track events throughout the lifecycle on the component. In this scenario, we’re using it to subscribe to new observables returned from chatService.getMessages once the component is mounted. The observable emits a new value for every new chat message and will update the list of displayed messages.

ngOnDestroy unsubscribes at the end of the component lifecycle.

You can find the complete source code to this tutorial here and also check below for the sample display of the application.

When you run the application try opening the same url in a different browser window and observe how the messages are displayed in real-time. Also using Google Chrome, hit right-click button, click the Network tab and the WS tab afterwards to see the messages return to client from the server.   

screenshot

Sign up for our Angular Course

Learn the most recent version and start building your own Angular apps

View Course Details