Angular2/typescript and SSE (EventSource)

Dunderdon picture Dunderdon · May 3, 2016 · Viewed 8.7k times · Source

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

Answer

Thierry Templier picture Thierry Templier · May 3, 2016

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