EventSource is not working in Angular 4

Viewed 6471

I am new to Angular 4 and I am trying to create an EventSource to subscribe and receive events. I started with the following code:­­­­

import { Injectable} from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class MyService implements OnInit {

  constructor(private http: Http) {
    const eventSource = new EventSource('/events');
    eventSource.onmessage = x => console.log(JSON.parse(x.data));
  }
}

I got the following error:

[ts] Cannot find name 'EventSource'.

Then, I added the following import:

import { EventSource } from 'eventsource';

An error appeared in the browser's console:

Uncaught (in promise): TypeError: 
__WEBPACK_IMPORTED_MODULE_2_eventsource_lib_eventsource_js__.EventSource is not a constructor

I also tried to add

"eventsource": "1.0.2"

to my package.json, re-install using npm install, launch the project using npm start, but the issue persisted.

2 Answers

Solution using native window.EventSource object:

import {NgZone, Injectable} from "@angular/core";
import {Observable} from "rxjs";

@Injectable()
export class SseService {

    eventSource: any = window['EventSource'];

    constructor(private ngZone: NgZone) {
    }

    observeStream(sseUrl: string): Observable<any> {
        return new Observable<any>(obs => {

            const eventSource = new this.eventSource(sseUrl);

            eventSource.onmessage = event => {

                let data = JSON.parse(event.data);

                // $apply external (window.EventSource) event data
                this.ngZone.run(() => obs.next(data));

            };
            // close connection when observer unsubscribe
            return () => eventSource.close();
        });
    }

}
Related