Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you detect network connectivity in Angular 2?

I am trying to write a component that will detect whether the app is online or offline so it can trigger another event. Is there a built-in function that can be leveraged?

like image 830
Farhan Islam Avatar asked Oct 24 '17 16:10

Farhan Islam


People also ask

How do you check the connectivity of a network?

Select the Start button, then type settings. Select Settings > Network & internet. The status of your network connection will appear at the top. Windows 10 lets you quickly check your network connection status.

Can be used to test network connectivity?

Ping is a network administration utility or tool used to test connectivity on an Internet Protocol (IP) network.

How do I know if JavaScript is connected to internet?

JavaScript has a function called navigator. This browser property can be used to determine if you are connected to the internet. It returns true or false depending on the status of the client's network and says whether the browser is online or offline easily.


1 Answers

  • To listen to and react to change, you need an event handler. In Angular, Observables are best
  • To be notified of the app coming online or going offline, rely on the online/offline events

    online$ = fromEvent(window, 'online');
    offline$ = fromEvent(window, 'offline');
    

Chain your other events to these:

online$.subscribe(e => this.syncWithServer());

Also see this article about navigator.onLine. Note that browsers don't implement this event uniformly. In some cases, "online" just means that the browser is connected to a local network, not the internet. To get more reliable information, you may need to test by trying to ping a remote server when the event fires.

online$ = fromEvent(window, 'online').pipe(
            switchMap(e => this.pingServer()),
            filter(e => e)
          );

offline$ = fromEvent(window, 'offline').pipe(
            switchMap(e => this.pingServer()),
            filter(e => !e)
          );

Where pingServer will make a remote request and return an observable that emits true when the request is successful, or false otherwise.

like image 181
BeetleJuice Avatar answered Oct 05 '22 23:10

BeetleJuice