如何在$http请求后检测该用户处于脱机状态

How to detect that user is offline after an $http request

本文关键字:于脱机 脱机 状态 用户 http 请求 检测      更新时间:2023-09-26

在AngularJs中使用$http服务请求失败后,我想测试网络连接(在线/离线)。当在错误处理程序中查找所有可用的响应参数时,我看不到任何可以帮助我的东西

感谢您的帮助,Olivier

请求代码:

$http({ method: method, url: url, data: data, headers: headers })
  .success(function (result) {
    deferred.resolve(result);
  })
  .error(function (data, status, headers, config, statusText) {
    console.log(data);
    console.log(status);
    console.log(headers);
    console.log(config);
    console.log(statusText);
    deferred.reject();
  });

控制台中的结果:

GET http://192.168.0.12:3000/test net::ERR_INTERNET_DISCONNECTED ionic.bundle.js:16185
 backEnd.js:25
0 backEnd.js:26
function (name) {
    if (!headersObj) headersObj =  parseHeaders(headers);
    if (name) {
      return headersObj[lowercase(name)] || null;
    }
    return headersObj;
  } backEnd.js:27
Object {method: "GET", transformRequest: Array[1], transformResponse: Array[1], url: "http://192.168.0.12:3000/test", data: null…} backEnd.js:28
undefined backEnd.js:29

如果你想简单地检测你是否在线,你可以使用:

if (navigator.onLine) {
  alert('online')
} else {
  alert('offline');
}

有关此和其他联机/脱机检查技术,请查看:http://www.html5rocks.com/en/mobile/workingoffthegrid/