[Fixed] How can you detect network connectivity in Angular 2?

Issue

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?

Solution

  • 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.

Leave a Reply

(*) Required, Your email will not be published