QuokMoon
QuokMoon

Reputation: 4425

Check web app is online or offline

Here it is a code to check application is online or offline :

 this.online$ = Observable.merge(
            Observable.of(navigator.onLine),
            Observable.fromEvent(window, 'online').map(() => true),
            Observable.fromEvent(window, 'offline').map(() => false)
        )
        this.online$.subscribe(isOnline=>{
            if(isOnline){
              console.log(isOnline);
            }else{
              console.log("you are offline");
              console.log(isOnline);
            }
        });

But it always return a true it means they are online but it's wrong result. I turned off system internet unlikely they return same result (true).

Upvotes: 2

Views: 3721

Answers (3)

Cédric M.
Cédric M.

Reputation: 113

Lightest version, that always return navigator.onLine value:

import { fromEvent, merge, of } from 'rxjs';
import { map } from 'rxjs/operators';

isOffline$ = merge(
  of(null),
  fromEvent(window, 'online'),
  fromEvent(window, 'offline')
).pipe(map(() => !navigator.onLine));

Upvotes: 2

Ketan Chaudhari
Ketan Chaudhari

Reputation: 556

import { fromEvent, merge, of } from 'rxjs';
import { mapTo } from 'rxjs/operators';


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

this.online$.subscribe((isOnline) =>{
  if(isOnline) {
    console.log(isOnline);
    } else {
      console.log("you are offline");
      console.log(isOnline);
    }
});

This will emit true or false based on the browsers online status.

Upvotes: 6

Ivan
Ivan

Reputation: 1366

I have the following code in my app:

// Adjust the imports if you use RxJS < 6.0.0-alpha.3.
import { BehaviorSubject, fromEvent } from 'rxjs';

/**
 * Whether the browser indicates that the device is online.
 */
export const onlineSubject = new BehaviorSubject<boolean>(true);

const handleOnlineChange = (online: boolean) => {
  if (online !== onlineSubject.getValue()) {
    onlineSubject.next(online);
  }
};

handleOnlineChange(navigator.onLine);

fromEvent(window, 'online').subscribe(() => handleOnlineChange(true));
fromEvent(window, 'offline').subscribe(() => handleOnlineChange(false));

Hope this does the trick for you.

Upvotes: 3

Related Questions