Angular and Server Sent Events (SSE)

bartoszgajda55

Bartosz Gajda

Posted on August 10, 2020

Angular and Server Sent Events (SSE)

In this post I will show you how to connect to Server Sent Events (SSE) source in Angular app. We will create a small prototype that will connect to Server Sent Events (SSE) endpoint using Event Source API, resulting in events wrapped into Observable and run inside Angular Zone.

Server-Sent Events *(SSE*) is a server push technology enabling a client to receive automatic updates from a server via HTTP connection. The Server-Sent Events EventSource API is standardized as part of HTML5 by the W3C.
*Wikipedia*

For this tutorial you will need following tools:

Creating clean Angular project

First let’s create a clean Angular project. Use the following Angular CLI command from your terminal to do so:

ng new angular-sse

This command creates a clean project and installs all dependencies. Luckily, this project doesn’t require any third party deps — Angular provides everything you need to interact with Server Sent Events (SSE)

Connecting to Server Sent Events (SSE) endpoint

Next, enter the project directory (*angular-sse *in my case), and create a new service using following terminal command:

ng generate service sse

As a result, the SseService is created and wired into the Angular project. Now, lets' write some actual code. The snippet below is the complete code of the SseService class:

import { Injectable, NgZone } from "@angular/core";
import { Observable } from "rxjs";

@Injectable({
  providedIn: "root"
})
export class SseService {
  constructor(private _zone: NgZone) {}

  getServerSentEvent(url: string): Observable<any> {
    return Observable.create(observer => {
      const eventSource = this.getEventSource(url);

      eventSource.onmessage = event => {
        this._zone.run(() => {
          observer.next(event);
        });
      };

      eventSource.onerror = error => {
        this._zone.run(() => {
          observer.error(error);
        });
      };
    });
  }

  private getEventSource(url: string): EventSource {
    return new EventSource(url);
  }
}

Resulting service creates a concise and easy to use interface for interacting with Server Sent Events (SSE). Here, we unify the logic used to connect to any endpoint that supports SSE.

In principle, this service connects to SSE endpoint using Event Source API, allowing to box this into Observable object. This Observable is then run inside the Angular Zone. This allows Angular to detect events and execute the underlying logic correctly.

Subscribing to Observable

Next, let’s create a component that subscribes to SSE endpoint using the SseService observable. Similarly to creating a service, using Angular CLI for that:

ng new component home

Furthermore, I will use this newly created HomeComponent to test the service and connect to testing SSE endpoint. Open the home.component.ts file and insert the following:

import { Component, OnInit } from "@angular/core";
import { SseService } from "src/app/services/sse/sse.service";

@Component({
  selector: "app-home",
  templateUrl: "./home.component.html",
  styleUrls: ["./home.component.scss"]
})
export class HomeComponent implements OnInit {
  constructor(private sseService: SseService) {}

  ngOnInit() {
    this.sseService
      .getServerSentEvent("http://localhost:8082/raw")
      .subscribe(data => console.log(data));
  }
}

The code above, connects to SSE endpoint (http://localhost:8082/raw in my case) using the SseService. After that, the events are logged into the console, for debugging.

Summary

In conclusion using Server Sent Events (SSE) in Angular is quite simple and allows for creating cool, reactive applications. I hope you have found this post useful. If so, don’t hesitate to like or share this post. Additionally you can follow me on my social media if you fancy so :)

💖 💪 🙅 🚩
bartoszgajda55
Bartosz Gajda

Posted on August 10, 2020

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

Sign up to receive the latest update from our blog.

Related

Angular and Server Sent Events (SSE)
angular Angular and Server Sent Events (SSE)

August 10, 2020