Angular2/TypeScript和SSE(EventSource)

7

首先,我对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)
    });
3个回答

6
事实上,TypeScript有两个方面需要考虑:
1. 编译时。编译器会检查语法错误和类型。对于类型,它依赖于d.ts文件,这些文件描述了对象/类的契约。
2. 执行时。如果对象存在于您的执行环境中,则代码将被执行。
在您的情况下,问题出现在编译时。
以下是EventSource的d.ts文件示例:https://github.com/sbergot/orgmodeserver/blob/master/src/ts/deps/EventSource.d.ts 您可以获取并引用它,在TypeScript文件的开头这样写:
/// <reference path="../<path-to>EventSource.d.ts"/>

5

你能告诉我如何为EventSource添加polyfill吗? - Akshay Busa

3
您需要指定EventSource是window的函数,并且需要传递参数。
const eventSource = new window['EventSource']("http://url")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接