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.
update
as sudheer suggested in answer below navigator.onLine
in working with angular2 but still not working properly why ?
working example here
As i have checked navigator is global object like window. You can use in in angular2 and it worked fine for me.
Safe Approach to listen to network states
Answers given above works well but are not considered safe approach.
1.Browser dependent objects like window should not be referenced directly, always check for platform.
2.Furthermore functionality like Network Connection must be encapsulated into a service.
Below is the ConnectionService which can be subscribed to listen network states. It follows the rxjs 6 style.
Complete Code
in component, you may listen by subscribing to monitor() or directly into HTML using async pipe.
Go with this simple Hack.
Working in angular 5 or later
write this in constructor of app.component.ts or your app bootstrap No need of any external library ..
(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:
component:
Using Angular 6+ and Rxjs 6+, you can do it in the following way:
Here is a demo (toggle network in dev tools)
Use this.
Without any external library.