Skip to content

Instantly share code, notes, and snippets.

@AnthonyGiretti
Created November 24, 2025 00:43
Show Gist options
  • Select an option

  • Save AnthonyGiretti/fe0cda9164b2960190b5d5b39a43f0cf to your computer and use it in GitHub Desktop.

Select an option

Save AnthonyGiretti/fe0cda9164b2960190b5d5b39a43f0cf to your computer and use it in GitHub Desktop.
Angular SSE handling
import { Injectable, NgZone } from '@angular/core';
import { Observable } from 'rxjs';
import { Country } from './country.model';
@Injectable({ providedIn: 'root' })
export class CountryStreamService {
private readonly url = 'https://localhost:5001/countries/stream';
constructor(private zone: NgZone) {}
streamCountries(): Observable<Country> {
return new Observable<Country>(observer => {
const eventSource = new EventSource(this.url);
// Listen to events named "country" (set on the server)
eventSource.addEventListener('country', (event: MessageEvent) => {
this.zone.run(() => {
const country = JSON.parse(event.data) as Country;
observer.next(country);
});
});
eventSource.onerror = error => {
this.zone.run(() => observer.error(error));
eventSource.close();
};
return () => eventSource.close();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment