7
votes

First of all, I`m quite new to ng2 and typescript.

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

3 Answers

6
votes

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"/>
5
votes
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

3
votes

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")