Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2/Typescript - Get server latency

I couldn't help myself searching the interwebs for an answer, so I will just ask straight away.

I'm running a frontend using angular2 and typescript, receiving data from a server.

Is there a way to setup a connection sending pings in specific intervals to get the server response time? I then want to display them in a chart using PrimeNG.

like image 882
Faigjaz Avatar asked Oct 25 '25 01:10

Faigjaz


1 Answers

You could try this PingService - just set the url to your url.

@Injectable()
export class PingService {
  pingStream: Subject<number> = new Subject<number>();
  ping: number = 0;
  url: string = "https://cors-test.appspot.com/test";

  constructor(private _http: Http) {
    Observable.interval(5000)
      .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);
          });
      });
  }
}

Use it in your component's constructor like so:

this._pingService.pingStream.subscribe(ping => {
  this.ping = ping;
})

And in your template just add this where you want to show the current ping:

{{ping | number:'1.0-0'}}ms

Working Plunker for example usage

like image 85
rinukkusu Avatar answered Oct 27 '25 16:10

rinukkusu