In Angular how to consume SSE ?
getServerSentEvent(url: string): Observable { return new Observable(observer => { const eventSource = new EventSource(url);
eventSource.onmessage = (event) => {
observer.next(event.data);
};
eventSource.onerror = (error) => {
observer.error(error);
};
return () => {
eventSource.close();
};
});
}
Add the state variables
messages: string[] = [];
subscription: Subscription;
Inside constructor or onInit subscribe for the event
this.subscription = this.sseService.getServerSentEvent('http://localhost:3000/events')
.subscribe((data: string) => {
console.log('event', data);
this.messages.push(data);
});