How can you detect network connectivity in Angular 2?

Safe Approach to listen to network states

Answers given above works well but are not considered safe approach.

1.Browser dependent objects should not be referenced directly, always check for platform.

2.Furthermore functionality like Network Connection must be encapsulated into a service.

Below is the ConnectionService which can be subscribed to listen network states. It follows the rxjs 6 style.

Complete Code

import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { Observable, fromEvent, merge, EMPTY } from 'rxjs';
import { isPlatformBrowser } from '@angular/common';
import { mapTo } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ConnectionService {

  private connectionMonitor: Observable<boolean>;

  constructor(@Inject(PLATFORM_ID) platform) {
if (isPlatformBrowser(platform)) {
  const offline$ = fromEvent(window, 'offline').pipe(startWith(!window.navigator.onLine), mapTo(false));
  const online$ = fromEvent(window, 'online').pipe(startWith(window.navigator.onLine), mapTo(true));
  this.connectionMonitor = merge(
    offline$, online$
  );
} else {
  this.connectionMonitor = EMPTY;
}



 }

  monitor(): Observable<boolean> {
    return this.connectionMonitor;
  }
}

in component, you may listen by subscribing to monitor() or directly into HTML using async pipe.


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


export class HomeComponent implements OnInit {
   public isOnline : boolean = navigator.onLine;
}

Another solution with basic javascript functions. Use this below code in app.component.ts file

constructor() {
    window.addEventListener("online", () => {
        alert ("Your browser is working online.");
    });
    window.addEventListener("offline", () => {
        alert ("Your browser is working offline.");
    });
}