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.
as sudheer suggested in answer below navigator.onLine
in working with angular2 but still not working properly why ? working example here
ping (This command will test for the Internet connectivity and DNS functionality.) Example: ping www.netgear.com, ping google.com.
(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.
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