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 possible with Angular 4.
I checked with https://github.com/HubSpot/offline
. I think this will not work for angular 4. Any one please suggest. Is this possible to use offlinejs for Angular 4 or any other alternatives?
Thanks Sarath C M
JavaScript has a function called navigator. This browser property can be used to determine if you are connected to the internet. It returns true or false depending on the status of the client's network and says whether the browser is online or offline easily.
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<boolean>( fromEvent(window, 'offline').pipe(map(() => false)), fromEvent(window, 'online').pipe(map(() => true)), new Observable((sub: Observer<boolean>) => { 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With