Angular and Server Sent Events (SSE)
Tags: angular, javascript, typescript, sse
Published: 2020-08-10 12:31:49

In this post I will show you how to connect to [Server Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) (SSE) source in [Angular ](https://angular.io/)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 ](https://angular.io/guide/observables)and run inside [Angular Zone](https://angular.io/api/core/NgZone).
>  ***Server-Sent Events **(**SSE**) is a [server push](https://en.wikipedia.org/wiki/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](https://en.wikipedia.org/wiki/HTML5) by the [W3C](https://en.wikipedia.org/wiki/World_Wide_Web_Consortium).*
>  [*Wikipedia](https://en.wikipedia.org/wiki/Server-sent_events)*

For this tutorial you will need following tools:

* [Node.js](https://nodejs.org/en/) — I use version 13.2.0

* [Angular CLI](https://cli.angular.io/) — I use version 8.3.20

## 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](https://developer.mozilla.org/en-US/docs/Web/API/EventSource), allowing to box this into Observable object. This [Observable ](https://angular.io/guide/observables)is then run inside the [Angular Zone](https://angular.io/api/core/NgZone). 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 :)

{% twitter 1241005941253963777 %}