事件源在Angular 4中无法正常工作

6

我是Angular 4的新手,正在尝试创建一个EventSource来订阅和接收事件。我从以下代码开始:

import { Injectable} from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class MyService implements OnInit {

  constructor(private http: Http) {
    const eventSource = new EventSource('/events');
    eventSource.onmessage = x => console.log(JSON.parse(x.data));
  }
}

我遇到了以下错误:

[ts] Cannot find name 'EventSource'.

然后,我添加了以下导入:

import { EventSource } from 'eventsource';

浏览器控制台中出现了一个错误:

Uncaught (in promise): TypeError: 
__WEBPACK_IMPORTED_MODULE_2_eventsource_lib_eventsource_js__.EventSource is not a constructor

我也尝试添加。
"eventsource": "1.0.2"

将以下代码添加到我的package.json中,然后使用npm install重新安装,使用npm start启动项目,但问题仍然存在。
2个回答

7

我猜问题在于这个库导出的是一个函数,而你期望得到一个对象。尝试导入所有内容并给它起一个名字:

import * as EventSource from 'eventsource';

然后你可以将其用作构造函数。


2
使用本地的window.EventSource对象解决方案:
import {NgZone, Injectable} from "@angular/core";
import {Observable} from "rxjs";

@Injectable()
export class SseService {

    eventSource: any = window['EventSource'];

    constructor(private ngZone: NgZone) {
    }

    observeStream(sseUrl: string): Observable<any> {
        return new Observable<any>(obs => {

            const eventSource = new this.eventSource(sseUrl);

            eventSource.onmessage = event => {

                let data = JSON.parse(event.data);

                // $apply external (window.EventSource) event data
                this.ngZone.run(() => obs.next(data));

            };
            // close connection when observer unsubscribe
            return () => eventSource.close();
        });
    }

}

1
window.EventSource 不是跨浏览器的解决方案。请查看:https://developer.mozilla.org/en-US/docs/Web/API/EventSource - Denis Reshetniak

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