EventSource在Angular 4中不起作用
发布时间:2020-12-17 17:51:50 所属栏目:安全 来源:网络整理
导读:我是Angular 4的新手,我正在尝试创建一个EventSource来订阅和接收事件.我从以下代码开始: import { Injectable} from '@angular/core';import { Http } from '@angular/http';@Injectable()export class MyService implements OnInit { constructor(private
我是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启动项目,但问题仍然存在. 解决方法
我假设,问题是这个库导出一个函数.你期待这个对象.尝试导入所有内容并为其命名: 从’eventsource’导入*作为EventSource; 比你可以用它作为构造函数.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |