Sarath
Sarath

Reputation: 1499

Check internet connection in web using Angular 4

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

Upvotes: 33

Views: 44577

Answers (13)

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.

Upvotes: 0

Kalim ul Haq
Kalim ul Haq

Reputation: 328

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

Upvotes: 1

Yogendra
Yogendra

Reputation: 534


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

navigator.onLine --> returns true or false

Upvotes: 1

Kodali444
Kodali444

Reputation: 1443

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>

Upvotes: 2

Biju B Adoor
Biju B Adoor

Reputation: 526

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

Upvotes: -1

Alok Srivastav
Alok Srivastav

Reputation: 61

    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
    }

Upvotes: 1

Alexsoyes
Alexsoyes

Reputation: 444

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

Upvotes: 2

Raj Anand
Raj Anand

Reputation: 51

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.

Upvotes: 0

jenish
jenish

Reputation: 171

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!!

Upvotes: -1

Dilshan Liyanage
Dilshan Liyanage

Reputation: 4568

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

Upvotes: 80

Soni Kumari
Soni Kumari

Reputation: 116

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

Upvotes: 0

vinesh
vinesh

Reputation: 4923

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.

Upvotes: 4

Sajeetharan
Sajeetharan

Reputation: 222722

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;

Upvotes: 22

Related Questions