Giter Club home page Giter Club logo

ng-connection-service's Introduction

Internet Connection Monitoring Service (Angular v9-v15)

Detects whether browser has an active internet connection or not in Angular application.

Detects whether your API Server is running or not in Angular application.

Note that, this library is being updated to support most of the Angular versions. Currently, it supports Angular v9 till v15, and verified with demos. Meanwhile, for Angular 8 and earlier versions, try installing package with version 1.0.4 npm i [email protected]. Stay tuned for updates.

Install

You can get it on npm.

npm install ng-connection-service --save

Setup

  • Import HttpClientModule and ConnectionServiceModule into your application AppModule
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { ConnectionServiceModule } from 'ng-connection-service';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    ConnectionServiceModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Usage - Check only internet connection status

  • Inject ConnectionService in Angular component's constructor, subscribe to monitor() method.
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ConnectionService, ConnectionServiceOptions, ConnectionState } from 'ng-connection-service';
import { Subscription, tap } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {
  title = 'demo';

  status!: string;
  currentState!: ConnectionState;
  subscription = new Subscription();

  constructor(private connectionService: ConnectionService) {
  }

  ngOnInit(): void {
    this.subscription.add(
      this.connectionService.monitor(options).pipe(
        tap((newState: ConnectionState) => {
          this.currentState = newState;

          if (this.currentState.hasNetworkConnection) {
            this.status = 'ONLINE';
          } else {
            this.status = 'OFFLINE';
          }
        })
      ).subscribe()
    );
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
}

Usage - Check YOUR API Server connection status

  • Inject ConnectionService in Angular component's constructor, subscribe to monitor() method. Here hasInternetConnection boolean property informs if given server URL passed via heartbeatUrl property is reachable or not.
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ConnectionService, ConnectionServiceOptions, ConnectionState } from 'ng-connection-service';
import { Subscription, tap } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {
  title = 'demo';

  status!: string;
  currentState!: ConnectionState;
  subscription = new Subscription();

  constructor(private connectionService: ConnectionService) {
  }

  ngOnInit(): void {
    const options: ConnectionServiceOptions = {
      enableHeartbeat: false,
      heartbeatUrl: 'https://localhost:4000',
      heartbeatInterval: 2000
    }
    this.subscription.add(
      this.connectionService.monitor(options).pipe(
        tap((newState: ConnectionState) => {
          this.currentState = newState;

          if (this.currentState.hasNetworkConnection && this.currentState.hasInternetAccess) {
            this.status = 'ONLINE';
          } else {
            this.status = 'OFFLINE';
          }
        })
      ).subscribe()
    );
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
}
  • Note that we have passed configuration object to monitor() function to watch application server status.
 const options: ConnectionServiceOptions = {
      enableHeartbeat: false,
      heartbeatUrl: 'https://localhost:5000',
      heartbeatInterval: 2000
    }

Demos

You can find demos in GitHub repository under directory projects/demo/.

API

You can configure the service using ConnectionServiceOptions configuration variable. Following options are available;

/**
 * Instance of this interface could be used to configure "ConnectionService".
 */
export interface ConnectionServiceOptions {
  /**
   * Controls the Internet connectivity heartbeat system. Default value is 'true'.
   */
  enableHeartbeat?: boolean;
  /**
   * Url used for checking Internet connectivity, heartbeat system periodically makes "HEAD" requests to this URL to determine Internet
   * connection status. Default value is "//internethealthtest.org".
   */
  heartbeatUrl?: string;
  /**
   * Interval used to check Internet connectivity specified in milliseconds. Default value is "30000".
   */
  heartbeatInterval?: number;
  /**
   * Interval used to retry Internet connectivity checks when an error is detected (when no Internet connection). Default value is "1000".
   */
  heartbeatRetryInterval?: number;
  /**
   * HTTP method used for requesting heartbeat Url. Default is 'head'.
   */
  requestMethod?: 'get' | 'post' | 'head' | 'options';

}

Demo

Working demo

License

MIT License © Balram Chavan

ng-connection-service's People

Contributors

dependabot[bot] avatar ultrasonicsoft avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ng-connection-service's Issues

geting error of defineInjectable

WARNING in ./node_modules/ng-connection-service/fesm5/ng-connection-service.js
35:59-75 "export 'defineInjectable' was not found in '@angular/core'
ℹ 「wdm」: Compiled with warnings.
///
ng-connection-service.js:35 Uncaught TypeError: Object(...) is not a function
at ng-connection-service.js:35
at Object../node_modules/ng-connection-service/fesm5/ng-connection-service.js (ng-connection-service.js:37)
at webpack_require (bootstrap:81)
at Object../src/app/app.component.ts (main.js:388)
at webpack_require (bootstrap:81)
at Object../src/app/app.module.ts (app.component.ts:10)
at webpack_require (bootstrap:81)
at Object../src/main.ts (environment.ts:36)
at webpack_require (bootstrap:81)
at Object.0 (main.ts:11)
(anonymous) @ ng-connection-service.js:35
./node_modules/ng-connection-service/fesm5/ng-connection-service.js @ ng-connection-service.js:37
webpack_require @ bootstrap:81
./src/app/app.component.ts @ main.js:388
webpack_require @ bootstrap:81
./src/app/app.module.ts @ app.component.ts:10
webpack_require @ bootstrap:81
./src/main.ts @ environment.ts:36
webpack_require @ bootstrap:81
0 @ main.ts:11
webpack_require @ bootstrap:81
checkDeferredModules @ bootstrap:43
webpackJsonpCallback @ bootstrap:30
(anonymous) @ main.js:1
client?719c:147 [WDS] Warnings while compiling.
warnings @ client?719c:147
onmessage @ socket.js:41
EventTarget.dispatchEvent @ sockjs.js:170
(anonymous) @ sockjs.js:883
SockJS._transportMessage @ sockjs.js:881
EventEmitter.emit @ sockjs.js:86
WebSocketTransport.ws.onmessage @ sockjs.js:2957
wrapFn @ zone.js:1166
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:421
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:188
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:496
invokeTask @ zone.js:1517
globalZoneAwareCallback @ zone.js:1543
client?719c:153 ./node_modules/ng-connection-service/fesm5/ng-connection-service.js
35:59-75 "export 'defineInjectable' was not found in '@angular/core'
warnings @ client?719c:153
onmessage @ socket.js:41
EventTarget.dispatchEvent @ sockjs.js:170
(anonymous) @ sockjs.js:883
SockJS._transportMessage @ sockjs.js:881
EventEmitter.emit @ sockjs.js:86
WebSocketTransport.ws.onmessage @ sockjs.js:2957
wrapFn @ zone.js:1166
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:421
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:188
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:496
invokeTask @ zone.js:1517
globalZoneAwareCallback @ zone.js:1543

Upgrade for Angular 8

Package "ng-connection-service" has an incompatible peer dependency to "@angular/core" (requires "^6.0.0-rc.0 || ^6.0.0" (extended), would install "8.0.0").

Does not work on windows 10

I tried using this in my project and it works on Android (chrome).
However on Windows 10 (chrome & firefox) it will always say it is online. Both in the 'working-demo' and in my own project.

Update:
I noticed that navigator.onLine also says true when I'm not online.

'heartbeatInterval' does not do anything

no matter what value i set the 'heartbeatInterval' property to, it always uses the default 2000ms heartbeat

    const options: ConnectionServiceOptions = {
      enableHeartbeat: true,
      heartbeatUrl: window.location.origin,
      heartbeatInterval: 20000, // should be twenty seconds
      heartbeatRetryInterval: 1000 // 1 second
    };
    this.connectionService.monitor(options)
    ...

Not working when loading offline app (service worker)

My app is offline available by the service worker. When I press "offline" in der Chrome dev tools my output message "offline" is shown in the app. But when I reload the page (using it offline with the service worker) the "offline" is not shown anymore. Is there a way to fix it or any workaround?

Readme issues

Usage - Check only internet connection status

the 'options' variable example under this readme section is not set or isn't in the code

Usage - Check YOUR API Server connection status

the 'options' variable is again incorrect for this part of the readme section

How to revitalize this project?

Seems like this project is dead :(

There have been no updates for 2 years. The latest ng-connection-service release only supports Angular v 6. As of today, we have Angular 9.

@ultrasonicsoft Could you please give a hint if there's any way to bring this project back to life? If you don't have time for this, maybe you could share ownership or allow someone else to commit to the master branch and make npm releases?

It would be really cool if the community could continue enjoying using this package

Update for Angular 7+

When trying to update Angular Version from 7.2.15 to the 8 via ng update, it gives me an error:
ackage "ng-connection-service" has an incompatible peer dependency to "@angular/core" (requires "^6.0.0-rc.0 || ^6.0.0" (extended), would install "8.0.0"). and Package "ng-connection-service" has an incompatible peer dependency to "@angular/common" (requires "^6.0.0-rc.0 || ^6.0.0" (extended), would install "8.0.0").
Can you please update peer dependency?

Piles of console error when http fails

The console.error can be replaced to throwError of rxjs or throw of javascript to prevent the piles of error in console when i do not want.
I faced issue of http error when network was down, and the console was constantly filled with errors, which i have no control on

if the methods throws error i can create a try catch block while subscribing the observable and decide what i want to do of error

tap(val => {
console.error('Http error:', val);
this.currentState.hasInternetAccess = false;
this.emitEvent();
}),

Not always working

I noticed that its not working when I disable the wifi on my desktop, my desktop is also connected through cable but that connection doesn't have internet, yet it shows as online

App not detecting the first state

When you build the production project and start that using a service work when you turn the internet off and reload the page, the service doesn't detect that you are offline, and i cant initialize the variable.

Angular 17.2.0 does not support ConnectionServiceModule?

I'm encountering an error in my Angular application related to the compatibility of the ng-connection-service library with Angular Ivy. When trying to import the ConnectionServiceModule from ng-connection-service into my Angular module, I'm getting the following error: Error: src/app/app.module.ts:39:5 - error NG6002: 'ConnectionServiceModule' does not appear to be an NgModule class.

39 ConnectionServiceModule ~~~~~~~~~~~~~~~~~~~~~~~

node_modules/ng-connection-service/lib/ng-connection-service.module.d.ts:1:22 1 export declare class ConnectionServiceModule { ~~~~~~~~~~~~~~~~~~~~~~~ This likely means that the library (ng-connection-service) which declares ConnectionServiceModule is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.

✖ Failed to compile.
Screenshot 2024-02-20 at 12 12 27 PM

Typo in the documentation

import { ConnectionService } from 'connection-service';

should read

import { ConnectionService } from 'ng-connection-service';

Thanks for this module :)

currentState is a boolean

Your example is wrong or outdated as I can see.

currentState is a boolean so

this.hasNetworkConnection = currentState.hasNetworkConnection;
this.hasInternetAccess = currentState.hasInternetAccess;

doesn't work

Does this work with Ivy?

I am trying to include the ConnectionServiceModule in my Angular 16 app module as such:

import { ConnectionServiceModule } from 'ng-connection-service';

and I get this error:
image

Exponential backoff

In a lot of cases, when the server is down and there are a lot of clients it is custom to not keep a interval constant but rather increase the delay between calls so that when the server returns the clients won't create a DDOS kind of scenario.

Would be nice to have this here I think...?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.