Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check internet connection in web using Angular 4

Tags:

angular

web

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

like image 885
user3541485 Avatar asked Oct 06 '17 05:10

user3541485


People also ask

How do I know if JavaScript is connected to Internet?

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.


1 Answers

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

like image 51
Dilshan Liyanage Avatar answered Oct 12 '22 06:10

Dilshan Liyanage