Internet connection monitoring in Angular6

Internet connection monitoring in Angular6

Apr 14, 2019 / Ramesh Mhetre

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 npm 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';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export 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



Similar Articles

Javascript Markdown parser: Markdown-it

Javascript Markdown parser: Markdown-it

Markdown-it is a javascript library/package which converts markdown text to HTML. Its very fast, efficient & easy to use within your project.
Read more...
Efficient admin template using Angular 7+, Bootstrap 4 and Nebular: ngx-admin

Efficient admin template using Angular 7+, Bootstrap 4 and Nebular: ngx-admin

The most popular admin dashboard based on Angular 7+, Bootstrap 4+ and Nebular. Free and Open Source for personal and commercial purposes.
Read more...