Internet connection monitoring in Angular

Abhishek Ankush
Frontend Weekly
Published in
2 min readMay 4, 2024

--

While working with different web applications I came across requirement of identifying if the application is online and serving the pages accordingly. Yes we do have something called as progressive web apps or PWA where we can serve the application in the offline mode. 😊

There are multiple approaches to achieve this.

  1. Using FormEvent
  2. Using Navigator
  3. Using library
  1. Using FormEvent:

I created a sample code to check and update UI for network connections.

import { Component } from '@angular/core';
import { Observable, Subscription, fromEvent } from 'rxjs';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'Internet-connection-example';
onlineEvent: Observable<Event> | undefined;
offlineEvent!: Observable<Event>;
subscriptions: Subscription[] = [];

connectionStatusMessage!: string;
connectionStatus!: string;

ngOnInit(): void {
/**
* Get the online/offline status from browser window
*/
this.onlineEvent = fromEvent(window, 'online');
this.offlineEvent = fromEvent(window, 'offline');
/**
* Get the online status as observable
*/
this.subscriptions.push(this.onlineEvent.subscribe(e => {
this.connectionStatusMessage = 'Back to online';
this.connectionStatus = 'online';
console.log('Online...');
}));

/**
* Get the offline status as observable
*/
this.subscriptions.push(this.offlineEvent.subscribe(e => {
this.connectionStatusMessage = 'Connection lost! You are not connected to internet';
this.connectionStatus = 'offline';
console.log('Offline...');
}));
}

ngOnDestroy(): void {
/**
* Unsubscribe all subscriptions to avoid memory leak
*/
this.subscriptions.forEach(subscription => subscription.unsubscribe());
}
}

2. Using Navigator:

Using navigator we can check the internet connection status only once. We can trick the same using observables

constructor() {
this.online$ = merge(
of(navigator.onLine),
fromEvent(window, 'online').pipe(mapTo(true)),
fromEvent(window, 'offline').pipe(mapTo(false))
);
}

3. Using library:

Internet Connection Monitoring Service is a library available to check internet connection. Please check their page provided as hyperlink.

Sample code for internet check:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { ConnectionService, ConnectionServiceOptions, ConnectionState } from 'ng-connection-service';
import { Subscription, tap } from 'rxjs';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {
title = 'demo';

status!: string;
currentState!: ConnectionState;
subscription = new Subscription();

constructor(private connectionService: ConnectionService) {
}

ngOnInit(): void {
this.subscription.add(
this.connectionService.monitor(options).pipe(
tap((newState: ConnectionState) => {
this.currentState = newState;

if (this.currentState.hasNetworkConnection) {
this.status = 'ONLINE';
} else {
this.status = 'OFFLINE';
}
})
).subscribe()
);
}

ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}

Conclusion:

Identifying internet connection status or API status is an architectural decision and design requirement. Browser support this identification with easy method.

I hope this article helps you in your use case. If you liked this article, please πŸ‘ below, so that other people can find it! 😊

Happy Coding!!

--

--