I am using an EventSource in my angular 6 project. When I try to run my project using ng serve
, I get the following error:
ERROR in ./node_modules/eventsource/lib/eventsource.js Module not found: Error: Can't resolve 'http' in '${MY_PATH}/node_modules/eventsource/lib'
This error appears the same for 'https' module. I tried to use the HttpClientModule
instead of the HttpModule
but it didn't work. I also tried to install the EventSource
explicitly by running npm install eventsource
, but the issue is still there.
The code that I'm using:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import * as EventSource from 'eventsource';
@Injectable({
providedIn: 'root'
})
export class MyService {
private eventSource: EventSource;
constructor(private http: HttpClient) {
this.eventSource = new EventSource('/subscribe');
this.eventSource.reconnectInterval = 1;
}
// Rest of the code omitted for clarity
}
I managed to solve the issue by using this event source which seems to be compatible with angular. To do so, run
npm install ng-event-source
. Then, in the code, use theEventSourcePolyfill
object instead ofEventSource
: