我是Angular 4的新手,正在尝试创建一个EventSource来订阅和接收事件。我从以下代码开始:
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));
}
}
我遇到了以下错误:
[ts] Cannot find name 'EventSource'.
然后,我添加了以下导入:
import { EventSource } from 'eventsource';
浏览器控制台中出现了一个错误:
Uncaught (in promise): TypeError:
__WEBPACK_IMPORTED_MODULE_2_eventsource_lib_eventsource_js__.EventSource is not a constructor
我也尝试添加。
"eventsource": "1.0.2"
将以下代码添加到我的package.json中,然后使用npm install重新安装,使用npm start启动项目,但问题仍然存在。