Angular2/typescript and SSE (EventSource)

为君一笑 提交于 2019-12-05 10:27:44

In fact, there are two things in TypeScript:

  • 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.

Here is a sample of d.ts file for EventSource: https://github.com/sbergot/orgmodeserver/blob/master/src/ts/deps/EventSource.d.ts

You can get it and reference it at the very beginning of your TypeScript file this way:

/// <reference path="../<path-to>EventSource.d.ts"/>
let eventSource = window['EventSource'];

TypeScript does not know about EventSource which is part of window. So you have to extract first.

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

You need to specify that EventSource is the function of window and also need to pass the parameter with it.

const eventSource = new window['EventSource']("http://url")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!