visit
window.addEventListener("load", () => {
this.networkStatus = navigator.onLine
window.addEventListener("online", () => {
this.networkStatus = true
});
window.addEventListener("offline", () => {
this.networkStatus = false
});
});
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