Created
November 24, 2025 00:43
-
-
Save AnthonyGiretti/fe0cda9164b2960190b5d5b39a43f0cf to your computer and use it in GitHub Desktop.
Angular SSE handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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