gpt4 book ai didi

angularjs - 如何使用 angularJs 检查用户是否有互联网连接

转载 作者:行者123 更新时间:2023-12-03 07:01:10 25 4
gpt4 key购买 nike

当用户尝试在没有互联网连接的情况下登录时,我只需要检查他/她是否已连接到互联网。

我尝试了以下代码:

if (status == '404') {
$scope.error="No internet connection";
return false;
}

但是即使我的 Web 服务连接失败,也会出现此状态 404。我需要区分两者是用户的互联网连接问题还是 Web 服务连接问题。

最佳答案

使用navigator.onLine

您可以使用 navigator.onLine 并将其包装在辅助变量上,如下所示 ( Credits to this answer )

myApp.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);
});

然后在 Controller 中观看:

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

但是这只是作为一个脏检查来了解电脑是否确实连接到网络,并不意味着互联网正在工作。

使用虚假的 AJAX 请求

您可以模拟向浏览器发出虚假请求的服务(警告:下面未经测试的代码)

myApp.service('Internet', function($http){
this.IsOk = function () {
return $http({ method: 'HEAD', url: '/' + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000) })
.then(function(response) {
var status = response.status;
return status >= 200 && status < 300 || status === 304;
});
}
});

然后在这种情况下使用一些东西:

myApp.controller('TestController', function(Internet){

Internet.IsOn().then(function(isok){
if(isok) {...} else {...}
});

});

this link中的请求模拟代码。

另请注意,它无法使用 localhost 工作,因为即使断开与互联网的连接,服务器也能工作。

关于angularjs - 如何使用 angularJs 检查用户是否有互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24121369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com