Internet connection monitoring in Angular6

Internet connection monitoring in Angular6


It's a pretty common requirement to monitor the internet connection in your Angular application on the client side & change the behavior of the application accordingly. We might want to show a message — “you are offline”, we might want to load cached data or we would user to take to “offline” page (route). Also as soon as internet connection is restored, we would like to make application functional without any user interaction.

We can achieve desired feature using window.ononline and window.onoffline events.

Its not really a tough thing to do this with core JS but luckily we have a package (ng-connection-service) for this.

You can install service via <a href="" target="_blank">npm</a> command:

npm i ng-connection-service

ng-connection-service Usage

  • Inject ConnectionService in Angular component's constructor.
  • Subscribe to monitor() method to get push notification whenever internet connection status is changed.
import { Component } from '@angular/core';
import { ConnectionService } from 'ng-connection-service';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export <span class="hljs-class">class AppComponent {
  status = 'ONLINE';
  isConnected = true;

  constructor(private connectionService: ConnectionService) {
    this.connectionService.monitor().subscribe(isConnected => {
      this.isConnected = isConnected;
      if (this.isConnected) {
        this.status = "ONLINE";
      else {
        this.status = "OFFLINE";

ng-connection-service Demo