Using Angular to Detect Network Connection Status - Online/Offline

Written by rameezrami | Published 2022/12/08
Tech Story Tags: angular | angular-development | programming | angular-programming | programming-languages | angular-tutorial | angular-top-story | programming-tips

TLDRWe need to properly unsubscribe the events we are listening to. We use the JavaScript way of checking Online/Online status. The code is used to check Online/Offline status. You can see the demo here: <https://angular-check-offline-online-online?file=src/app/app.component.ts> You can also check the code here: http://stackblitz.io> or check it out: <http://://://www.jim.com/jim/angular/core/app-compiler/html/.via the TL;DR App

We might all be familiar with the JavaScript way of checking Online/Offline status. But in the case of Angular, we need to properly unsubscribe the events we are listening to. Otherwise, it might lead to unnecessary behaviors and memory leaks.

Plain JS

window.addEventListener("load", () => {
  this.networkStatus = navigator.onLine

  window.addEventListener("online", () => {
    this.networkStatus = true
  });

  window.addEventListener("offline", () => {
    this.networkStatus = false
  });
});

Angular Way

import { Component, OnDestroy, OnInit, VERSION } from '@angular/core';

import { fromEvent, merge, of, Subscription } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  networkStatus: boolean = false;
  networkStatus$: Subscription = Subscription.EMPTY;

  constructor() {}

  ngOnInit(): void {
    this.checkNetworkStatus();
  }

  ngOnDestroy(): void {
    this.networkStatus$.unsubscribe();
  }

  checkNetworkStatus() {
    this.networkStatus = navigator.onLine;
    this.networkStatus$ = merge(
      of(null),
      fromEvent(window, 'online'),
      fromEvent(window, 'offline')
    )
      .pipe(map(() => navigator.onLine))
      .subscribe(status => {
        console.log('status', status);
        this.networkStatus = status;
      });
  }
}

You can see the demo here.

or check the code here

Happy coding!!! 🎉🎉🎉


Also published here.


Written by rameezrami | Rameez AKA TheThinkster is a JavaScript enthusiast and a full stack software engineer.
Published by HackerNoon on 2022/12/08