EventSource not working in angular 6 due to module http and https

4.8k Views Asked by At

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
}
3

There are 3 best solutions below

0
On BEST ANSWER

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 the EventSourcePolyfill object instead of EventSource:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { EventSourcePolyfill } from 'ng-event-source';

@Injectable({
  providedIn: 'root'
})
export class MyService {
    private eventSource: EventSourcePolyfill;

    constructor(private http: HttpClient) {
        this.eventSource = new EventSourcePolyfill('/subscribe', { heartbeatTimeout: 1000, connectionTimeout: 1000 });
    }

    // Rest of the code omitted for clarity
}
1
On

I don't really know this package, but it's look like it has nothing to do with Angular or Angular http module. Have you read the browser polyfill section in the documation ? https://www.npmjs.com/package/eventsource

I think this package is created for NodeJs but you can use it on browsser side but you need to add some extra files

0
On

Try removing an import

import * as EventSource from 'eventsource';