Angular Server-Sent Events Client

21.0.0 · active · verified Wed Apr 22

ngx-sse-client is an Angular library providing a robust client for Server-Sent Events (SSE), designed as an alternative to the native `EventSource` API. Currently at stable version 21.0.0, this package typically releases new major versions in alignment with Angular's own major releases, ensuring compatibility with the latest Angular ecosystem. Its key differentiator lies in leveraging Angular's `HttpClient` for SSE stream requests, which enables seamless integration with `HttpInterceptor` for authentication, logging, and error handling. It also supports flexible HTTP methods (e.g., POST instead of just GET) and exposes event streams as RxJS Observables, aligning with Angular's reactive programming paradigm. This allows for more advanced control and error management compared to traditional `EventSource` implementations, which lack interceptor support and direct Observable integration.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates injecting the `SseClient` service, subscribing to an SSE stream with custom options (keep-alive, reconnection delay, event response type), including HTTP headers for authorization, and using a POST method. It also shows handling both `MessageEvent` and `ErrorEvent` responses within the subscription.

import { Component, OnInit } from '@angular/core';
import { HttpHeaders } from '@angular/common/http';
import { SseClient } from 'ngx-sse-client';

@Component({
  selector: 'app-root',
  template: `<h1>SSE Stream Example</h1><p>Check console for events.</p>`,
})
export class AppComponent implements OnInit {
  constructor(private sseClient: SseClient) {}

  ngOnInit(): void {
    const headers = new HttpHeaders().set('Authorization', `Basic YWRtaW46YWRtaW4=`);

    // Example of subscribing to an SSE stream with custom options and POST method
    this.sseClient.stream(
      '/api/subscribe', // Replace with your SSE endpoint
      { keepAlive: true, reconnectionDelay: 1_000, responseType: 'event' },
      { headers },
      'POST'
    ).subscribe({
      next: (event) => {
        if (event.type === 'error') {
          const errorEvent = event as ErrorEvent;
          console.error('SSE Error Event:', errorEvent.error, errorEvent.message);
        } else {
          const messageEvent = event as MessageEvent;
          console.info(`SSE Message (${messageEvent.type}):`, messageEvent.data);
        }
      },
      error: (err) => {
        console.error('SSE Subscription Error:', err);
      },
      complete: () => {
        console.log('SSE Stream Completed.');
      }
    });
  }
}

view raw JSON →