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.
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.
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();
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With