如何在 AngularJs 中检查互联网连接 [英] How to check internet connection in AngularJs
问题描述
这是我在 vanilla 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);
我的项目中有角度控制器和模块.我应该把上面的代码放在哪里?它应该在全局上下文中执行,而不是分配给某个控制器.可能有某种全局控制器吗?
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);
});
注意:我在 $apply
方法中包装了对根作用域变量的更改,以通知 Angular 某些内容已更改.
NOTE: I am wrapping changing of root scope's variable in $apply
method to notify Angular that something was changed.
之后你可以:
在控制器中:
$scope.$watch('online', function(newStatus) { ... });
在 HTML 标记中:
In HTML markup:
<div ng-show="online">You're online</div>
<div ng-hide="online">You're offline</div>
这是一个工作 Plunker:http://plnkr.co/edit/Q3LkiI7Cj4RWBNRLEJUA?p=preview
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屋!