Search code examples
springangularfluxserver-sent-eventseventsource

Receiving Flux SSE in Angular 5


I have succesfully implemented this mechanism in my application: https://vividcode.io/Spring-5-WebFlux-with-Server-Sent-Events/ I can receive events with curl every second, as shown in the example.

My problem is: I cannot receive these events in Angular 5. I have tried many things. Currently my service code looks like this:

public getMigrationProgress(processName: string): Observable<any> {
    let headers: HttpHeaders = new HttpHeaders();
    headers = headers.append('X-Authorization', this._sessionService.getAuthToken());
    headers = headers.append('accept', 'text/event-stream');

    let url = config.restApi.url + this.getResource() + '/' + processName;
    return Observable.create(observer => {
        let eventSource = new EventSourcePolyfill(url, { headers: headers });
        eventSource.onmessage = (event => {
            observer.next(event);
            this.zone.run(() => {
                console.log('prpprpr');
            });
        });
        eventSource.onopen = (event) => {
            observer.next(event);
        };
        eventSource.onerror = (error) => {
            if (eventSource.readyState === 0) {
                console.log('The stream has been closed by the server.');
                eventSource.close();
                observer.complete();
            } else {
                observer.error('EventSource error: ' + error);
            }
        };
    });
}

It only opens connection, does not receive events (Method onopen works once, onmessage - never). Server sends them though.

Any ideas how to fix this?


Solution

  • Turned out that if you set event name on server, you cannot receive it by onmessage method.

    In the example the event name was set to "random". In order to receive it you have to do it like this:

    eventSource.addEventListener('random', function (event) {
        console.log(event);
    });