简体   繁体   English

angular怎么查询离线和在线

[英]How can check offline and online in angular

I have been getting an error from the service call when browse is in offline mode.当浏览处于离线模式时,我从服务调用中收到错误。 How can check off-line mode and want to block my service call when the browser is the offline mode?当浏览器处于离线模式时,如何检查离线模式并想阻止我的服务调用?

I suggest you to use Offline.js 我建议你使用Offline.js

they have templates and other stuff to work with . 他们有模板和其他东西可以使用。 you can check out their documentation and see how it works . 你可以查看他们的文档 ,看看它是如何工作的。

it gets you the current state of the connection by returning the "up" or "down" result , or you can bind and event to it and use it across you'r application . 它通过返回“向上”或“向下”结果来获取连接的当前状态,或者您可以绑定和事件到它并在您的应用程序中使用它。

this is what they say about their library : 这就是他们对图书馆的看法:

Offline.js is a library to automatically alert your users when they've lost internet connectivity, like Gmail. Offline.js是一个图书馆,可以在用户丢失互联网连接时自动提醒用户,例如Gmail。

It captures AJAX requests which were made while the connection was down, and remakes them when it's back up, so your app reacts perfectly. 它捕获在连接断开时创建的AJAX请求,并在备份时重新创建它们,因此您的应用程序反应完美。

It has a number of beautiful themes and requires no configuration. 它有许多漂亮的主题,不需要配置。

good luck and have fun. 祝好运并玩得开心点。

Check for navigator.onLine and based on this value decide whether to send request or not. 检查navigator.onLine并根据此值决定是否发送请求。

if (navigator.onLine) {
    $http.get('url').success(function() {});
}
else {
    // no req
}

Angular way: 角度方式:

Use $q service - A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing. 使用$q service - 一种帮助您异步运行函数的服务,并在完成处理时使用它们的返回值(或异常)。 https://docs.angularjs.org/api/ng/service/ $q https://docs.angularjs.org/api/ng/service/ $ q

The best way that I would know would be to intercept the HTTP handler, if its a 401 / 501/ etc. then to handle it according 我知道的最好的方法是截取HTTP处理程序,如果它是401/501 /等,然后根据它来处理它

angular.module('myApp', ['myApp.services'], 
    function ($httpProvider) {

    var interceptor = ['$rootScope', '$q', function ($rootScope, $q) {

        function success(response) {
            return response;
        }

        function error(response) {
            var status = response.status; // error code

            if ((status >= 400) && (status < 500)) {
                $rootScope.broadcast("AuthError", status);
                return;
            }

            if ( (status >= 500) && (status < 600) ) {
                $rootScope.broadcast("ServerError", status);
                return;
            }

            // otherwise
            return $q.reject(response);

        }

        return function (promise) {
            return promise.then(success, error);
        }

    }];
    $httpProvider.responseInterceptors.push(interceptor);

then in your code that listens for the on of, just add in 然后在你的代码中监听on,只需添加

$rootScope.$on("ServerError", someServerErrorFunction);

Source: How to detect when online/offline status changes 来源: 如何检测在线/离线状态何时发生变化

Online/offline detection cannot be 100% accurately decided because.network status can vary for a number of reasons.在线/离线检测不能 100% 准确地决定,因为网络状态可能因多种原因而变化。

Still, if you want an implementation of the same with Angular+NGRX, You can find more details here.尽管如此,如果您想要使用 Angular+NGRX 实现相同的实现,您可以在此处找到更多详细信息。

https://hackernoon.com/using-angular-to-detect.network-connection-status-onlineoffline https://hackernoon.com/using-angular-to-detect.network-connection-status-onlineoffline

import { Component, OnDestroy, OnInit, VERSION } from '@angular/core';

import { fromEvent, merge, of, Subscription } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  networkStatus: boolean = false;
  networkStatus$: Subscription = Subscription.EMPTY;

  constructor() {}

  ngOnInit(): void {
    this.checkNetworkStatus();
  }

  ngOnDestroy(): void {
    this.networkStatus$.unsubscribe();
  }

  checkNetworkStatus() {
    this.networkStatus = navigator.onLine;
    this.networkStatus$ = merge(
      of(null),
      fromEvent(window, 'online'),
      fromEvent(window, 'offline')
    )
      .pipe(map(() => navigator.onLine))
      .subscribe(status => {
        console.log('status', status);
        this.networkStatus = status;
      });
  }
}

You can see the demo here . 你可以在这里看到演示

or check the code here 或在此处查看代码

Happy coding!!!编码快乐!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM