我在我的 angular 6 项目中使用了 EventSource。当我尝试使用ng serve
运行我的项目时,出现以下错误:
./node_modules/eventsource/lib/eventsource 中的错误.js模块不是 找到:错误:无法解析中的"http" '${MY_PATH}/node_modules/eventsource/lib'
此错误在">https"模块中显示相同。我尝试使用HttpClientModule
而不是HttpModule
但没有用。我还尝试通过运行npm install eventsource
来显式安装EventSource
,但问题仍然存在。
我正在使用的代码:
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
}
尝试删除导入
import * as EventSource from 'eventsource';
我真的不知道这个包,但它看起来与 Angular 或 Angular http 模块无关。您是否阅读了文档中的浏览器 polyfill部分?https://www.npmjs.com/package/eventsource
我认为这个包是为 NodeJs 创建的,但您可以在浏览器端使用它,但您需要添加一些额外的文件
我设法通过使用这个似乎与 angular 兼容的事件源来解决这个问题。为此,请运行npm install ng-event-source
。然后,在代码中,使用EventSourcePolyfill
对象而不是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
}