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.

#typescript #javascript #angular #servers #front-end-development

Angular and Server Sent Events (SSE)
47.10 GEEK