I'm using Angular 10 and trying to listen to server-sent events from a node.js REST server. I'm a noob with Angular (this is a school project.) Anyway, all the tutorials I've found create a service that implements the EventSource and subscribes to the chunks as they are received. Everything compiles ok, but when I browse to a page that uses the service I get this error "NullInjectorError: No provider for EventSource". Can anybody provide a reference that might help or tell me what I need to do to get past the error?
To be clear, I am not creating a new EventSource class but using what I understand to be a JavaScript built-in class (https://developer.mozilla.org/en-US/docs/Web/API/EventSource).
Removing "private _eventSource: EventSource" resolved the problem, which raises another question (I think I may have stumbled on my answer.) Is it the case that one cannot declare a variable of a built-in JavaScript type like EventSource?
Here is my code...
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);
})
}
});
}
}
It would be easier to help if we could see some code fragments but looking at error
NullInjectorError: No provider for EventSource
There are some missing dependencies in Angular dependency injection docs, which might mean that somewhere in your code you have created service class like
export class EventSource { ... }
and then in another one you are trying to provide it in constructor
class AnotherClass{
constructor(private myEventSource: EventSource)
}
but for it to work you would need to let DI know about your new class docs which could be done by adding annotation
@Injectable({
providedIn: 'root',
})
export class EventSource {
...
}
Other possibility is that you wanted to use already available javascript class EventSource
docs then instead of passing it to constructor try to simply create it in constructor
class AnotherClass{
private myEventSource
constructor(){
this.myEventSource = new EventSource(..)
}
}
If that was the problem you can later provide it in Angular DI as well this was proposed as potential quick fix.