Receiving messages from socket.io in Angular

lucianopinheiro

Luciano Pinheiro

Posted on October 2, 2023

Receiving messages from socket.io in Angular

Scenario

You have a flask server serving websocket via socket.io and need to connect from an Angular client.

Solution

In Angular:

  1. Create a module (optional)
  2. Create a websocket service inside that module
  3. Inject the websocket service into the component who will handle the messages
  4. Create the methods to handle messages inside that component

Create a module and websocket service

Create a standard module and a standard service

ng g m ws
ng g s ws/websocket
Enter fullscreen mode Exit fullscreen mode

You must create a service consisting only of an instance of a socket connection. We need the service to keep only one connection to the server at the beginning of service. Don't forget to enable CORS on server. Your websocket service will look like this:

// /app/ws/web-socket.service.ts
import { Injectable } from '@angular/core';
import { io } from 'socket.io-client';

@Injectable({
  providedIn: 'root',
})
export class WebSocketService {
  private socket: any = undefined;

  constructor() {
    if (!this.socket) {
      this.socket = io('http://localhost:5000/');
    }
  }

  public getSocket() {
    return this.socket;
  }
}

Enter fullscreen mode Exit fullscreen mode

Don't forget to install socket.io-client on your Angular project.

The client component

You must then inject your service into a component who will use the connection and intercept the messages.

/ //app.component.ts
import { Component } from '@angular/core';
import { WebSocketService } from './ws/web-socket.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  socket: any;
  messages: string[] = [];

  // Inject the service
  constructor(private webSocketService: WebSocketService) {
    this.socket = this.webSocketService.getSocket();

    // in this component you define what to do
    // with received event of type 'message'
    this.socket.on('message', (data: any) => {
      this.messages.push(data);
    });

    // when receiving a 'connect' event, send a message to server
    this.socket.on('connect', () => {
      const message = 'myevent';
      this.socket.emit(message, { data: "I'm connected!" });
    });
}
Enter fullscreen mode Exit fullscreen mode

Using this approach, you can connect to a server and define what to do with the received messages, of emit new messages to the server in a simple way, separating concerns as a service and a controller.

💖 💪 🙅 🚩
lucianopinheiro
Luciano Pinheiro

Posted on October 2, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related