@cognizone/a2-sse
v3.0.3
Published
Angular wrapper around the browser's native `EventSource` API, exposing an observable-based interface for SSE connections. Requires: **Angular >= 20 for v1.1.x** **Angular >= 21 for v3.0.x**
Keywords
Readme
@cognizone/a2-sse (Server Side Events)
Angular wrapper around the browser's native EventSource API, exposing an observable-based interface for SSE connections.
Requires:
Angular >= 20 for v1.1.x
Angular >= 21 for v3.0.x
Installation
npm i @cognizone/a2-sse// TODO Mariana - is it still valid ?
Setting up
- Provide the
SseWrapperFactoryservice into the module where you'll use the SSE functionality (in theprovidersarray) - Create a handler service to communicate with the sse functionality, e.g.
log-listener.service.ts
Inside that service;
// import the Sse wrapper classes
import { SseWrapper, SseWrapperFactory } from '@cognizone/a2-sse';// define an instance of sseWrapper
private sseWrapper: SseWrapper<string>;
// inject the SseWrapperFactory class
constructor(private readonly sseWrapperFactory: SseWrapperFactory, ...) {}You'll need to create an instance of sseWrapper and initialize it. Internally, it will establish the sse connection.
triggerSseConnection(): void {
const uri = 'http:your-sse-api-endpoint';
this.sseWrapper = this.sseWrapperFactory.create<string>(uri);
this.sseWrapper.init();
}You can also pass in a second parameter to the create method, which is an optional configuration object of the following blueprint:
{
eventSourceInit: {
withCredentials: boolean // (defaults to true)
}
}Example usage:
Once you've initialized the sseWrapper instance, you can listen to
- the reconnection state of the SSE connection (
this.sseWrapper.open$) - the ready state of the connection (
this.sseWrapper.readyState$) - the errors thrown from the connection (
this.sseWrapper.error$) - the "message" typed events of the connection (
this.sseWrapper.message$)
using the above-mentioned observable values.
The SseWrapper supports custom event types, too:
listenToMessages(): Observable<MessageEvent<string>> {
// listen to "message", "myCustomType1" and "myCustomType2" type events
// together
const messages$ = merge(
this.sseWrapper.message$,
this.sseWrapper.getEventsOfTypes(['myCustomType1', 'myCustomType2']),
);
// or separately
const messages$ = merge(
this.sseWrapper.message$,
this.sseWrapper.getEventsOfTypes('myCustomType1'),
this.sseWrapper.getEventsOfTypes('myCustomType2')
);
return messages$
.pipe(
// do your thing
);
}When you'd like to close your connection, you can use the .close() function of the SseWrapper:
closeSseConnection(): void {
this.sseWrapper.close();
this.resetStoredLogs();
}Key Features
- SSE Wrapper Factory: Factory service for creating EventSource wrappers
- Event Source Management: Observable-based event handling for connection state, messages, and errors
- Custom Event Types: Support for listening to custom event types in addition to standard message events
