如何使用angularJs检查用户是否已连接互联网

编程入门 行业动态 更新时间:2024-10-23 03:16:28
本文介绍了如何使用angularJs检查用户是否已连接互联网的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

When an user attempts to log in without Internet connection, I just need to check whether he/she is connected to internet or not.

我尝试了以下代码:

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

但是,即使我的Web服务无法连接,也会出现此状态404.如果是用户的Internet连接问题还是Web服务连接问题,我都需要对两者进行区分.

But this status 404 comes even when my Web Service failed to connect. I need to differentiate both, if is the user's internet connection issue or the Web Service connection issue.

推荐答案

使用 navigator.onLine

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

Using navigator.onLine

You can use navigator.onLine and wrap it on a helper variable, like this (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); });

,然后在控制器中观看:

and then watch it in the controller:

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

但是只是一种肮脏的检查,以了解PC是否实际上已连接到网络,并不意味着互联网正在运行.

But that just serves as a dirty check to know if the PC is actually connected to a network, not meaning that the internet is working.

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

You can mock a service that does a fake request to a browser (warning: non-tested code below)

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

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

And then use something in this context:

myApp.controller('TestController', function(Internet){ Internet.IsOn().then(function(isok){ if(isok) {...} else {...} }); });

此链接中的请求模拟代码.

还请注意,它不能使用 localhost 进行工作,因为即使断开Internet连接,服务器也可以正常工作.

Also note that it will not work using localhost, because the server will work even when disconnected to the internet.

更多推荐

如何使用angularJs检查用户是否已连接互联网

本文发布于:2023-11-27 20:09:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639429.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:互联网   如何使用   用户   angularJs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!