We all might 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, we might cause 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: https://angular-check-offline-online.stackblitz.io
or check the code here: https://stackblitz.com/edit/angular-check-offline-online?file=src/app/app.component.ts
Happy coding!!! 🎉🎉🎉
Top comments (0)