Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to detect ERR_INTERNET_DISCONNECTED by a built in method in Angular 2+

Is there a way to detect ERR_INTERNET_DISCONNECTED by a built-in method in Angular 2+ so I can warn the user? Or perhaps thru JS?

like image 423
Average Joe Avatar asked Nov 05 '17 20:11

Average Joe


2 Answers

Not sure about Angular, but the Navigator interface exposed on the global window object has a method for determining whether or not a browser is working online.

navigator.onLine returns a Boolean indicating whether the browser is working online. Doesn't get any simpler than that. Read the DOM docs for a more detailed description.

Example implementation:

if(navigator.onLine) { // true|false
    // ...
}

In addition to checking for the property value, you can hook into offline and online events:

window.addEventListener('online', (e) => console.log(e, "you're online"));
window.addEventListener('offline', (e) => console.log(e, "you're offline"));

Then, if the user goes offline, you can freeze the UI, show relevant messages or provide an offline experience (e.g., save data to localStorage until user comes online).

like image 162
Govind Rai Avatar answered Oct 08 '22 03:10

Govind Rai


I use the following method

define in your class online$: Observable<boolean>;

and inside constructor

this.online$ = Observable.merge(
  Observable.of(navigator.onLine),
  Observable.fromEvent(window, 'online').mapTo(true),
  Observable.fromEvent(window, 'offline').mapTo(false)
)

also add the imports

import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx'; 

Use it in template

<p *ngIf="(online$ | async) == false" >
  <ngb-alert [dismissible]="false">
    <strong>Warning!</strong> Better check yourself, you're not connected to internet.
  </ngb-alert>
</p>

you can also use it as a service.

like image 45
Hareesh Avatar answered Oct 08 '22 02:10

Hareesh