【问题标题】:Angular 10 - Server Sent Events - Missing EventSourceAngular 10 - 服务器发送事件 - 缺少事件源
【发布时间】:2021-02-19 19:05:30
【问题描述】:

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

明确地说,我不是在创建新的 EventSource 类,而是使用我理解的 JavaScript 内置类 (https://developer.mozilla.org/en-US/docs/Web/API/EventSource)。

删除“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);
        })
      }
    });
  }
}

【问题讨论】:

    标签: angular provider eventsource


    【解决方案1】:

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

    NullInjectorError: 没有 EventSource 的提供者

    Angular 依赖注入 docs 中缺少一些依赖项,这可能意味着您在代码中的某个位置创建了类似的服务类 export class EventSource { ... } 然后在另一个你试图在构造函数中提供它

    class AnotherClass{
      constructor(private myEventSource: EventSource)
    }
    

    但要使其正常工作,您需要让 DI 知道您的新课程 docs,这可以通过添加注释来完成

    @Injectable({
      providedIn: 'root',
    })
    export class EventSource {
        ...
    }
    

    另一种可能是你想使用已经可用的javascript类EventSourcedocs而不是将它传递给构造函数尝试简单地在构造函数中创建它

    class AnotherClass{
      private myEventSource
      constructor(){
        this.myEventSource = new EventSource(..)
      }
    }
    

    如果这是问题所在,您可以稍后在 Angular DI 中提供它,这也是作为潜在的快速解决方案提出的。

    【讨论】:

      猜你喜欢
      • 2020-06-20
      • 1970-01-01
      • 2017-04-23
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 2015-09-24
      • 2015-06-16
      • 2013-08-20
      相关资源
      最近更新 更多