首先,我对ng2和typescript都比较陌生。
我的目标是在Angular2组件中实现服务器发送事件。我已经按照早期帖子中提到的示例进行了操作,但是我的问题是“EventSource”对象未被识别(在VS Code中显示为红色下划线)。
我不确定是否缺少某些引用...... 我的引用如下:
<!-- IE required polyfills, in this exact order -->
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
<script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
这是我实现EventSource客户端的方法:
ngOnInit() {
const observable = Observable.create(observer => {
const eventSource = new EventSource(/API_URL); //Cannot find EventSource
eventSource.onmessage = x => observer.next(x.data);
eventSource.onerror = x => observer.error(x);
return () => {
eventSource.close();
};
});
observable.subscribe({
next: guid => {
this.zone.run(() => this.someStrings.push(guid));
},
error: err => console.error('something wrong occurred: ' + err)
});