How to check internet connection in AngularJs

Angularjs

Angularjs Problem Overview


This is how I would check internet connection in vanilla javascript:

setInterval(function(){
    if(navigator.onLine){
        $("body").html("Connected.");
    }else{
        $("body").html("Not connected.");
    }
},1000);

I have angular controllers and modules in my project. Where should I put the code above? It should be executed in global context and not be assigned to a certain controller. Are there some kind of global controllers maybe?

Angularjs Solutions


Solution 1 - Angularjs

First of all, I advise you to listen to online/offline events.

You can do it this way in AnguarJS:

var app = module('yourApp', []);

app.run(function($window, $rootScope) {
      $rootScope.online = navigator.onLine;
      $window.addEventListener("offline", function() {
        $rootScope.$apply(function() {
          $rootScope.online = false;
        });
      }, false);

      $window.addEventListener("online", function() {
        $rootScope.$apply(function() {
          $rootScope.online = true;
        });
      }, false);
});

NOTE: I am wrapping changing of root scope's variable in $apply method to notify Angular that something was changed.

After that you can:

In controlller:

$scope.$watch('online', function(newStatus) { ... });

In HTML markup:

 <div ng-show="online">You're online</div>
 <div ng-hide="online">You're offline</div>

Here is a working Plunker: http://plnkr.co/edit/Q3LkiI7Cj4RWBNRLEJUA?p=preview

Other solution could be to broadcast online/offline event. But in this case you need to initialize current status upon loading and then subscribe to event.

Solution 2 - Angularjs

It's definitely not as nice, but you could just try an AJAX request to your web server; it'll either succeed or time out.

Also, the HubSpot/offline project looks really good.

Solution 3 - Angularjs

Your options:

  • addEventListener on the window, document, or document.body.

  • setting the .ononline or .onoffline properties on document or
    document.body to a JavaScript Function object.

  • specifying ononline="..." or onoffline="..." attributes on the tag in the HTML markup

I will demonstrate the easiest.

In you controller

document.body.onoffline = function() {
   alert('You are offline now');
   $scope.connection = 'offline' 
}

document.body.ononline = function() {
   alert('You are online again');
   $scope.connection = 'online' 
}

Check $scope.connection variable before you try to send requests around.

Solution 4 - Angularjs

For Angular 2+ you can use ng-speed-test:

  1. Just install:
npm install ng-speed-test --save
  1. Inject into your module:
import { SpeedTestModule } from 'ng-speed-test';

@NgModule({
   ...
   imports: [
       SpeedTestModule,
       ...
   ],
   ...
})
export class AppModule {}
  1. Use service to get speed:
import {SpeedTestService} from 'ng-speed-test';

@Injectable()
export class TechCheckService {
  constructor(
    private speedTestService:SpeedTestService
  ) {
    this.speedTestService.getMbps().subscribe(
      (speed) => {
        console.log('Your speed is ' + speed);
      }
    );
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUpCatView Question on Stackoverflow
Solution 1 - AngularjsValentyn ShybanovView Answer on Stackoverflow
Solution 2 - AngularjsJon OnstottView Answer on Stackoverflow
Solution 3 - AngularjsCharlieView Answer on Stackoverflow
Solution 4 - AngularjsJeremyView Answer on Stackoverflow