I am using Angular 4 for my application development. I need to check If the network connection is available for its have any Connection issue using Angular for. Is it possib
We don't need any libraries for this however public onlineOffline: boolean = navigator.onLine; will do the trick but this is just a one time check. We need to treat this value as an observable so whenever the online status change we are updated. For this rxjs will help.
Import these
import { Observable, Observer, fromEvent, merge } from 'rxjs';
import { map } from 'rxjs/operators';
Add this method
createOnline$() {
return merge(
fromEvent(window, 'offline').pipe(map(() => false)),
fromEvent(window, 'online').pipe(map(() => true)),
new Observable((sub: Observer) => {
sub.next(navigator.onLine);
sub.complete();
}));
}
Subscribe to this event from your constructur or ngOnInit
this.createOnline$().subscribe(isOnline => console.log(isOnline));
Note: Im using Angular 8.1 and rxjs 6.5.2