33

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

1

13 Answers 13

80

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

Sign up to request clarification or add additional context in comments.

9 Comments

nice solution! love it!
Working fine in Angular 8.2.14 and rxjs 6.5.3
I love you! now i know how to make any var obseravle thanks bro
@tercou1 I am still using it even in angular 11
gives error for Angular9.1.12 and rxjs6.6.0 error TS2339: Property 'subscribe' does not exist on type '() => Observable<boolean>'.
|
22

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;

5 Comments

It will check in every page load is it right?. Without page refresh if the connection is gone i need to notify the user. And its reconnected that also need to inform. How can i make like that?
It always returns True
@Sajeetharan I am using the Same code as posted in the answer but it always returns true. Why?
@PrashantPimpale check my answer.
@DilshanLiyanage okay
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.

1 Comment

Can you show an example of how pinging google would work to check internet connection?
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();
      })
    );
  }

Comments

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>

Comments

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
    }

1 Comment

Please always describe what you are doing in your answer. It should be updated or removed. Read How to answer before you provide more answers ^^
1

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

navigator.onLine --> returns true or false

Comments

1

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

Comments

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

2 Comments

There is open issue for ng-connection-service as this library does not work on Angular 8 or above
The code written will only work in Angular 7 or its previous version.
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.

Comments

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.

Comments

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

Comments

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

1 Comment

this answer is already given above, how it is different from above one ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.