如何检查AngularJs互联网连接 [英] How to check internet connection in AngularJs

查看:124
本文介绍了如何检查AngularJs互联网连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我怎么会为您在香草的javascript互联网连接:

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

我在我的项目角度控制器和模块。我应该在哪里放置code以上?它应该在全球范围内被执行,而不是被分配到一个特定的控制器。是否有某种全局控制器的可能?

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?

推荐答案

首先,我劝你要听的在线/离线事件的。

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

您可以做到这一点在AnguarJS这种方式:

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.

之后,您可以:

在controlller:

In controlller:

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

在HTML标记:

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

下面是一个工作Plunker:<一href=\"http://plnkr.co/edit/Q3LkiI7Cj4RWBNRLEJUA?p=$p$pview\">http://plnkr.co/edit/Q3LkiI7Cj4RWBNRLEJUA?p=$p$pview

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.

这篇关于如何检查AngularJs互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆