I've encountered an error while attempting to subscribe to my observable in a Server Sent Event class that observes other components and sends information to them. Is anyone familiar with how to resolve this issue?
Here is the Server Sent Event class:
@Injectable()
export class ServerSentEvent implements OnInit{
public observable : Observable<any>;
ngOnInit(){
var errorCount = 0;
this.observable = Observable.create(observer => {
var eventSource = new EventSource(filterUrl);
eventSource.onmessage = (event: any)=>{
console.log("received val: " + JSON.parse(JSON.parse(event.data).payload).value);
observer.next(JSON.parse(JSON.parse(event.data).payload).value);
}
eventSource.onerror=(error: any)=>{
errorCount++;
if(error.targer.readyState === 0 && errorCount > 5){
eventSource.close();
observer.error();
}
}
return() => {
eventSource.close();
};
});
}
}
And here is my LightController class:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers:[ServerSentEvent]
})
export class LightControler implements OnInit{
connected : boolean;
light : boolean;
public button = (<HTMLInputElement>document.getElementById("check-toggle"));
public slider = (<HTMLInputElement>document.getElementById("light-slide"));
public slid = (<HTMLProgressElement>document.getElementById("light-bar"));
public constructor(
private http : HttpClient,
private serverSentEvent: ServerSentEvent){
this.serverSentEvent.observable.subscribe(
{
next: val =>{
console.log("light val: "+ val);
this.slid.value = val;
if (val >= 1){
this.light = true;
this.button.checked = true;
}
else{
this.light = false;
this.button.checked = false;
}
},
error: error =>{
setTimeout(()=> serverSentEvent.ngOnInit(), 1000);
}
}
);
}
The error occurs at this point: this.serverSentEvent.observable.subscribe()
TypeError: undefined is not an object (evaluating 'this.serverSentEvent.observable.subscribe')
It seems that the ngOnInit of the ServerSentEvent isn't initialized when the constructor of the LightControler is executed, causing an attempt to subscribe to a non-existent observable.
To fix this issue, I must call serverSentEvent.ngOnInit() before subscribing to the observable.