Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EventSource is not working in Angular 4

Tags:

angular

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.

like image 877
Joe Avatar asked Jun 04 '17 18:06

Joe


2 Answers

I assume, that problem is that this library exports a function. And you expect the object. Try to import everything and give it a name: import * as EventSource from 'eventsource'; Than you can use it as a constructor.

like image 158
Denis Reshetniak Avatar answered Oct 10 '22 05:10

Denis Reshetniak


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();
        });
    }

}
like image 45
Ondřej Machala Avatar answered Oct 10 '22 03:10

Ondřej Machala