Subscribe Us

Using Angular to Detect Network Connection Status – Online/Offline

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.

L O A D I N G
. . . comments & more!



Using Angular to Detect Network Connection Status – Online/Offline
Source: Trends Pinoy

Post a Comment

0 Comments