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!!

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Frontend Weekly
Frontend Weekly

Published in Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Abhishek Ankush
Abhishek Ankush

Written by Abhishek Ankush

Software Architect | Tech Blogger

Responses (1)

What are your thoughts?

It should be noted that the mentioned package for monitoring connectivity is nearly 200k, and accomplishes its monitoring using fromEvent also;
this.subscription.add(fromEvent(window, 'online')

1