Utilizing a Service to periodically "ping" my server every 2.5 seconds, I am able to retrieve the response time from the server by using observables.
My implementation also involves angular 2 and typescript.
Now, I am facing an issue where I want to be able to stop (unsubscribe) the service upon button click. Initially, this functionality works as intended. The button is designed to act as a toggle - subscribing if not already subscribed, and unsubscribing vice versa. However, I am encountering difficulties when attempting to resubscribe.
Below is the snippet of code defining my service:
export class PingService {
pingStream: Subject<number> = new Subject<number>();
ping: number = 0;
url: string = url.href;
constructor(private _http: Http) {
Observable.interval(2500)
.subscribe((data) => {
let timeStart: number = performance.now();
this._http.get(this.url)
.subscribe((data) => {
let timeEnd: number = performance.now();
let ping: number = timeEnd - timeStart;
this.ping = ping;
this.pingStream.next(ping);
});
});
}
}
The following code shows the function triggered on button click:
toggleSubscription() {
if (this.pingService.pingStream.isUnsubscribed) {
this.pingService.pingStream.subscribe(ping => {
this.ping = ping;
NTWDATA.datasets[0].data.pop();
NTWDATA.datasets[0].data.splice(0, 0, this.ping);
})
}
else {
this.pingService.pingStream.unsubscribe();
}
}
I have instantiated the PingService within the constructor of my appcomponent which then displays the data in a chart. Upon clicking the button for the first time, the service stops and no further data updates occur. Subsequent clicks yield no change despite the `this.pingService.pingStream.isUnsubscribed` returning true.
In addition, an "ObjectUnsubscribedError" is encountered upon the initial button click.
If anyone has any insights or solutions to offer, your help would be greatly appreciated! Thank you!