paint-brush
Using Angular to Detect Network Connection Status - Online/Offlineby@Thinkster
6,655 reads
6,655 reads

Using Angular to Detect Network Connection Status - Online/Offline

by The ThinksterDecember 8th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

We 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/.
featured image - Using Angular to Detect Network Connection Status - Online/Offline
The Thinkster HackerNoon profile picture


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.