Angular2/打字稿和SSE(EventSource) [英] Angular2/typescript and SSE (EventSource)
问题描述
首先,我对ng2和打字稿很陌生.
First of all, I`m quite new to ng2 and typescript.
Im试图完成的工作是在Angular2组件中实现Server-Sent事件. 我已经按照此处早期文章中提到的示例进行操作,但是我的问题是无法识别"EventSource"对象(VS代码中的红色下划线).
What Im trying to accomplish is to implement Server-Sent events in Angular2 component. I have followed the examples mentioned in earlies posts here, but my problem is that the "EventSource" object is unrecognized (red underline, in VS Code).
我不确定我是否缺少一些参考资料... 我的参考是:
Im not sure if I`m missing some references... My references are:
<!-- 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>
这是我如何植入事件源客户端的方法:
This is how I have Implemeted the eventsource client:
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)
});
推荐答案
实际上,TypeScript中有两件事:
In fact, there are two things in TypeScript:
- 编译时间.编译器检查语法错误和类型.关于类型,它依赖于
d.ts
文件,该文件可以在描述对象/类合同的文件中看到. - 执行时间.如果对象存在于您的执行环境中,则将执行代码.
- The compilation time. The compiler checks for syntax errors and types. Regarding types, it relies on
d.ts
files that can be seen at files described contracts of objects / classes. - The execution time. If the object is present into your execution environment, the code will be executed.
在您的情况下,问题出在编译时.
In your case, the problem is at compilation time.
这里是EventSource的d.ts文件的示例: https://github.com/sbergot/orgmodeserver/blob/master/src/ts/deps/EventSource.d.ts
Here is a sample of d.ts file for EventSource: https://github.com/sbergot/orgmodeserver/blob/master/src/ts/deps/EventSource.d.ts
您可以通过以下方式在TypeScript文件的开头获取并引用它:
You can get it and reference it at the very beginning of your TypeScript file this way:
/// <reference path="../<path-to>EventSource.d.ts"/>
这篇关于Angular2/打字稿和SSE(EventSource)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!