I am trying to create a Server Sent Event class that will observe other component and send information to them but I've got an error when I try to subscribe to my observable.
this is my 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 this is my lightControler 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 is on the this.serverSentEvent.observable.subscribe()
TypeError: undefined is not an object (evaluating 'this.serverSentEvent.observable.subscribe')
Does anyone know how to fix that or what am I doing wrong?
EDIT
the ngOnInit of the ServerSentEvent wasn't launch when the constructor of the lightControler was so i tried to subscribe to an observable that wasn't existing.
I need to call the serverSentEvent.ngOnInit() before subscribing to the observable.
console.log("received val: " + JSON.parse(JSON.parse(event.data).payload).value);- yoonjesung