Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether user has internet connection or not in Angular2?

Tags:

http

angular

How I would check internet connection in Angular2 at the time of API hitting, whenever in my app API is hit to server sometimes user is offline (i mean without internet connection) so how would i check the internet connectivity ? is there some special status code for internet connectivity ? or something else ?

PS:- i found navigator.onLine in angularJs but seems not working in angular2.

  • Source - How to check internet connection in AngularJs

update

as sudheer suggested in answer below navigator.onLine in working with angular2 but still not working properly why ? working example here

like image 261
Pardeep Jain Avatar asked Sep 19 '16 10:09

Pardeep Jain


People also ask

Which command that will used to check the Internet connectivity?

ping (This command will test for the Internet connectivity and DNS functionality.) Example: ping www.netgear.com, ping google.com.


1 Answers

(2018) Code updated for rxjs6

It totally works with angular2. Obviously it's different from angularJS because neither $scope nor $apply exist anymore. RxJS makes this easy, though! Tested on Chrome 53:

template:

<p>{{online$ | async}}</p> 

component:

import { Observable, fromEvent, merge, of } from 'rxjs'; import { mapTo } from 'rxjs/operators';  @Component({ /* ... */ }) export class MyComponent {   online$: Observable<boolean>;    constructor() {     this.online$ = merge(       of(navigator.onLine),       fromEvent(window, 'online').pipe(mapTo(true)),       fromEvent(window, 'offline').pipe(mapTo(false))     );   } } 

Think about what 'offline' means for your use case!

An unplugged ethernet cable and a 3KB/s EDGE connection likely have the same implications for your app although the latter means you're not technically offline!

From a programmer's point-of-view being connected wirelessly with a very poor signal is actually a lot worse than being truely disconnected because it's a lot harder to detect!

The above code returning a false value means your absolutely offline as in disconnected. It returning true doesn't necessarily indicate that there's a practically usable connection.

like image 164
j2L4e Avatar answered Oct 10 '22 15:10

j2L4e