我刚接触到角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启动项目,但问题仍然存在。
发布于 2017-06-04 19:52:43
我想,这个问题是这个库导出了一个函数。而你期待的是物体。尝试导入所有东西,并给它起一个名称:import * as EventSource from 'eventsource';,而不是您可以使用它作为构造函数。
发布于 2017-10-29 10:14:35
使用本机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();
});
}
}https://stackoverflow.com/questions/44357641
复制相似问题