我是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
启动项目,但问题仍然存在。
答案 0 :(得分:6)
我认为,问题是这个库导出了一个函数。你期待这个对象。尝试导入所有内容并为其命名:
import * as EventSource from 'eventsource';
比你可以用它作为构造函数。
答案 1 :(得分:2)
使用原生 window.EventSource 对象的解决方案:
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();
});
}
}