32

I am using Angular 4 for my application development. I need to check If the network connection is available for its have any Connection issue using Angular for. Is it possible with Angular 4.

I checked with https://github.com/HubSpot/offline . I think this will not work for angular 4. Any one please suggest. Is this possible to use offlinejs for Angular 4 or any other alternatives?

Thanks Sarath C M

onetwo12
  • 2,359
  • 5
  • 23
  • 34
Sarath
  • 1,459
  • 3
  • 22
  • 38
  • 3
    Possible duplicate of [How to check whether user has internet connection or not in Angular](https://stackoverflow.com/questions/39571231/how-to-check-whether-user-has-internet-connection-or-not-in-angular2) – Ramesh Rajendran Oct 06 '17 at 05:30

13 Answers13

78

We don't need any libraries for this however public onlineOffline: boolean = navigator.onLine; will do the trick but this is just a one time check. We need to treat this value as an observable so whenever the online status change we are updated. For this rxjs will help.

Import these

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

Add this method

  createOnline$() {
    return merge<boolean>(
      fromEvent(window, 'offline').pipe(map(() => false)),
      fromEvent(window, 'online').pipe(map(() => true)),
      new Observable((sub: Observer<boolean>) => {
        sub.next(navigator.onLine);
        sub.complete();
      }));
  }

Subscribe to this event from your constructur or ngOnInit

this.createOnline$().subscribe(isOnline => console.log(isOnline));

Note: Im using Angular 8.1 and rxjs 6.5.2

Dilshan Liyanage
  • 4,440
  • 2
  • 31
  • 33
21

You do not have to use any library for this, you can use navigator global object like window. You can use in in angular4

public onlineOffline: boolean = navigator.onLine;
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
4

I created a class called NetworkConnection which checks status of network connection. Here is code sample

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';

export enum ConnectionStatusEnum {
  Online,
  Offline
}

export class NetworkConnection {

  public static status: ConnectionStatusEnum = ConnectionStatusEnum.Online;
  private static online$: Observable<string>;
  private static offline$: Observable<string>;

  public static init() {
    NetworkConnection.online$ = Observable.fromEvent(window, 'online');
    NetworkConnection.offline$ = Observable.fromEvent(window, 'offline');

    NetworkConnection.online$.subscribe(e => {
      console.log('Online');
      NetworkConnection.status = ConnectionStatusEnum.Online;
    });

    NetworkConnection.offline$.subscribe(e => {
      console.log('Offline');
      NetworkConnection.status = ConnectionStatusEnum.Offline;
    });
  }

  constructor() {
    NetworkConnection.init();
  }

}

new NetworkConnection();

And you can use it like

import { NetworkConnection, ConnectionStatusEnum } from './ConnectionStatus';
....
if(NetworkConnection.status == ConnectionStatusEnum.Offline) {
    // do something
}
....

Additionally, if you want to check connection to internet, you can periodically ping sites like www.google.com instead of online/offline events. OR combination of both the approaches.

vinesh
  • 4,745
  • 6
  • 41
  • 45
2

A solution for RXJS 5.4.1 with Angular 4 based on @Dilshan Liyanage answer.

import { Observable } from 'rxjs/Observable';
import { fromEvent } from 'rxjs/observable/fromEvent';
import { Observer } from 'rxjs/Observer';

   /**
   * Return an observable with a boolean based on internet connection status
   */
  public checkInternetConnection(): Observable<boolean> {
    return Observable.merge<boolean>(
      fromEvent(window, 'online').map(() => true),
      fromEvent(window, 'offline').map(() => false),
      new Observable((sub: Observer<boolean>) => {
        sub.next(navigator.onLine);
        sub.complete();
      })
    );
  }
Alexsoyes
  • 444
  • 4
  • 12
2

In angular 11 below code is worked for me. My requirement is if wifi connection is disabled from internet router, we should show some message to user.

::::::::::1 St STEP:(app.ts):::::::::::::::


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))
  );
  }
}

:::::::::::2nd STEP:(app.html):::::::::::

<router-outlet cfBlockCopyPaste *ngIf="(online$ | async)"></router- 
 outlet>
 <div *ngIf="!(online$ | async)">
     <b>Please check your internet connection, then try again</b>
 </div>
Kodali444
  • 1,283
  • 1
  • 17
  • 21
1

    if(navigator.onLine) {
     alert("You are Online")
    }
    else {
     alert("You are Offline")
    }

navigator.onLine --> returns true or false

Viplav Soni
  • 1,489
  • 13
  • 18
Yogendra
  • 504
  • 5
  • 13
1
    import { Injectable } from '@angular/core';
    import {
        HttpRequest,
        HttpHandler,
        HttpEvent,
        HttpInterceptor
    } from '@angular/common/http';
    import { Observable } from 'rxjs/Observable';
    
    @Injectable()
    export class InternetInterceptor implements HttpInterceptor {
        constructor() { }
    
        intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            // check to see if there's internet
            if (!window.navigator.onLine) {
                // if there is no internet, throw a HttpErrorResponse error
                // since an error is thrown, the function will terminate here
                return Observable.throw(new HttpErrorResponse({ error: 'Internet is required.' }));
    
            } else {
                // else return the normal request
                return next.handle(request);
            }
        }
    }


and put this in providers of app.module.ts
{
        provide: HTTP_INTERCEPTORS,
        useClass: InternetInterceptorService,
        multi: true
    }
  • Please always describe what you are doing in your answer. It should be updated or removed. Read [How to answer](https://stackoverflow.com/help/how-to-answer) before you provide more answers ^^ – finnmglas Jul 21 '20 at 08:10
0

For the required task, There is a npm package, ng-connection-service. Below is the complete code:

import { Component,OnInit } from '@angular/core';
import { ConnectionService } from 'ng-connection-service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'internet-connection-check';
  status = 'ONLINE'; //initializing as online by default
  isConnected = true;

  constructor(private connectionService:ConnectionService){
    this.connectionService.monitor().subscribe(isConnected => {
      this.isConnected = isConnected;
      if(this.isConnected){
        this.status = "ONLINE";
      } else {
        this.status = "OFFLINE"
      }
      alert(this.status);
    });
  }
  ngOnInit(){

  }

}

Also you can find the working complete code over: click here

Soni Kumari
  • 126
  • 1
  • 5
  • 2
    There is open issue for [ng-connection-service](https://github.com/ultrasonicsoft/ng-connection-service/issues/23) as this library does not work on Angular 8 or above – Ivan Hušnjak Jan 15 '20 at 13:00
  • 1
    The code written will only work in Angular 7 or its previous version. – Soni Kumari Jan 19 '20 at 04:52
0

There is an option to check if your browser is online/offline via navigator.onLine The thing is, if navigator.onLine returns false, it means you are offline. But, returning true does not 100% make sure you are online. The reason is very simple and that is the implementation of the browser.

From the official documentation link Navigator.onLine

Browsers implement this property differently.

In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking

In Firefox and Internet Explorer, switching the browser to offline mode sends a false value. Until Firefox 41, all other conditions return a true value; testing actual behavior on Nightly 68 on Windows shows that it only looks for LAN connection like Chrome and Safari giving false positives.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Raj Anand
  • 41
  • 4
0

The simplest solution is

import { fromEvent } from 'rxjs';

fromEvent(window, 'online').subscribe((resp: any) => {
   console.log(resp);
   console.log('online');
});

fromEvent(window, 'offline').subscribe((resp: any) => {
   console.log(resp);
   console.log('offline');
});
Kalim ul Haq
  • 196
  • 1
  • 10
0

navigator.online won't give correct network status, In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet.

Instead of using navigator.online, the best workaround is to call an API from Angular side. If there in no network, then the connection will fail and, thus, the error callback will be triggered.so you can write your own logic inside the error block to handle the offline functionality.

-1

You do not have to use any library for this, you can handle this by this few lines of code.

Add this below code into your comman error handler service file file name errors-handlers-services.ts

if (string.includes(<<error message>>)) {
      window.location.reload();
 }

This code block is working for me. maybe this code snippet helps you!!

jenish
  • 171
  • 2
  • 8
-1

Detecting internet connection status in Angular application

We can achieve desired feature using window.ononline and window.onoffline events.

You can install service via npm command:

npm i ng-connection-service

Subscribe to monitor() method to get push notification whenever internet connection status is changed

import { Component } from '@angular/core';
import { ConnectionService } from 'ng-connection-service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  status = 'ONLINE';
  isConnected = true;

  constructor(private connectionService: ConnectionService) {
    this.connectionService.monitor().subscribe(isConnected => {
      this.isConnected = isConnected;
      if (this.isConnected) {
        this.status = "ONLINE";
      }
      else {
        this.status = "OFFLINE";
      }
    })
  }
}
Biju B Adoor
  • 528
  • 4
  • 6