7

首先,我对 ng2 和 typescript 很陌生。

我试图完成的是在 Angular2 组件中实现 Server-Sent 事件。我已经按照此处早期文章中提到的示例进行操作,但我的问题是无法识别“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>

这就是我实现事件源客户端的方式:

   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)
    });
4

3 回答 3

6

实际上,TypeScript 中有两件事:

  • 编译时间。编译器检查语法错误和类型。关于类型,它依赖于d.ts可以在描述对象/类合同的文件中看到的文件。
  • 执行时间。如果对象存在于您的执行环境中,则将执行代码。

在您的情况下,问题出在编译时。

这是 EventSource 的 d.ts 文件示例:https ://github.com/sbergot/orgmodeserver/blob/master/src/ts/deps/EventSource.d.ts

您可以通过以下方式在 TypeScript 文件的开头获取并引用它:

/// <reference path="../<path-to>EventSource.d.ts"/>
于 2016-05-03T12:11:04.890 回答
5
let eventSource = window['EventSource'];

TypeScript 不知道作为窗口一部分的 EventSource。所以你必须先提取。

见:https ://github.com/OasisDigital/sse-a2-example/blob/master/src/app/sse.ts

于 2017-08-30T12:15:13.270 回答
3

您需要指定 EventSource 是 window 的函数,并且还需要传递参数。

const eventSource = new window['EventSource']("http://url")
于 2019-06-27T11:26:31.270 回答