Angular 10-服务器发送的事件-缺少EventSource

Angular 10-服务器发送的事件-缺少EventSource,angular,provider,eventsource,Angular,Provider,Eventsource,我正在使用Angular 10,并尝试侦听node.js REST服务器发送的事件。我是Angular的noob(这是一个学校项目)。无论如何,我发现的所有教程都创建了一个服务,实现EventSource并在收到块时订阅它们。一切都可以编译,但当我浏览到使用该服务的页面时,会出现以下错误“NullInjectorError:No provider for EventSource”。有谁能提供一个参考资料来帮助我,或者告诉我需要做些什么来克服这个错误 明确地说,我不是在创建一个新的EventSou

我正在使用Angular 10,并尝试侦听node.js REST服务器发送的事件。我是Angular的noob(这是一个学校项目)。无论如何,我发现的所有教程都创建了一个服务,实现EventSource并在收到块时订阅它们。一切都可以编译,但当我浏览到使用该服务的页面时,会出现以下错误“NullInjectorError:No provider for EventSource”。有谁能提供一个参考资料来帮助我,或者告诉我需要做些什么来克服这个错误

明确地说,我不是在创建一个新的EventSource类,而是在使用我所理解的JavaScript内置类()

删除“private _eventSource:eventSource”解决了这个问题,这又引出了另一个问题(我想我可能是偶然发现了我的答案。)是不是不能声明像eventSource这样的内置JavaScript类型的变量

这是我的密码

import { Injectable, NgZone } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { Facility } from '../models/facility.model'
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MyClass {

  constructor( 
    private _http: HttpClient,
    private _zone: NgZone,
    private _eventSource: EventSource   // removing this resolved the error
  ) { }


  getMyEventSourceStream() {

    return new Observable((observer) => {
      const eventSource = new EventSource(this._summaryUrl);

      eventSource.onopen = (event) => {
        console.log(event);
      }

      eventSource.onmessage = (event) => {
        console.log(event);
        this._zone.run(() => {
          observer.next(event);
        })
      };

      eventSource.onerror = (error) => {
        this._zone.run(() => {
          observer.error(error);
        })
      }
    });
  }
}

如果我们可以看到一些代码片段,但看到错误,那么就更容易提供帮助

NullInjectorError:没有EventSource的提供程序

角度依赖项注入中缺少一些依赖项,这可能意味着您在代码中的某个地方创建了服务类,如
导出类EventSource{…}
然后在另一个类中尝试在构造函数中提供它

class AnotherClass{
  constructor(private myEventSource: EventSource)
}
class AnotherClass{
  private myEventSource
  constructor(){
    this.myEventSource = new EventSource(..)
  }
}
但要让它工作,您需要让DI知道您的新类,这可以通过添加注释来完成

@Injectable({
  providedIn: 'root',
})
export class EventSource {
    ...
}
另一种可能性是,您希望使用已经可用的javascript类
EventSource
,然后尝试在构造函数中创建它,而不是将其传递给构造函数

class AnotherClass{
  constructor(private myEventSource: EventSource)
}
class AnotherClass{
  private myEventSource
  constructor(){
    this.myEventSource = new EventSource(..)
  }
}
如果这是一个问题,您可以稍后在Angular DI中提供它,这是一个潜在的快速解决方案