简体   繁体   English

如何在 AngularJs 中检查互联网连接

[英]How to check internet connection in AngularJs

This is how I would check internet connection in vanilla javascript:这就是我在 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 .首先,我建议你多听线上/线下事件

You can do it this way in AnguarJS:你可以在 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);
});

NOTE: I am wrapping changing of root scope's variable in $apply method to notify Angular that something was changed.注意:我正在$apply方法中包装更改根范围的变量,以通知 Angular 某些内容已更改。

After that you can:之后你可以:

In controlller:在控制器中:

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

In HTML markup:在 HTML 标记中:

 <div ng-show="online">You're online</div>
 <div ng-hide="online">You're offline</div>

Here is a working Plunker: http://plnkr.co/edit/Q3LkiI7Cj4RWBNRLEJUA?p=preview这是一个工作的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.但在这种情况下,您需要在加载时初始化当前状态,然后订阅事件。

It's definitely not as nice, but you could just try an AJAX request to your web server;这绝对不是很好,但您可以尝试向您的 Web 服务器发送 AJAX 请求; it'll either succeed or time out.它要么成功,要么超时。

Also, the HubSpot/offline project looks really good.此外, HubSpot/离线项目看起来非常好。

Your options:您的选择:

  • addEventListener on the window, document, or document.body.在窗口、文档或 document.body 上添加事件监听器。

  • setting the .ononline or .onoffline properties on document or在文档上设置 .ononline 或 .onoffline 属性或
    document.body to a JavaScript Function object. document.body 到 JavaScript Function 对象。

  • specifying ononline="..." or onoffline="..." attributes on the tag in the HTML markup在 HTML 标记中的标记上指定 ononline="..." 或 onoffline="..." 属性

I will demonstrate the easiest.我将演示最简单的。

In you controller在你的控制器中

document.body.onoffline = function() {
   alert('You are offline now');
   $scope.connection = 'offline' 
}

document.body.ononline = function() {
   alert('You are online again');
   $scope.connection = 'online' 
}

Check $scope.connection variable before you try to send requests around.在尝试发送请求之前检查 $scope.connection 变量。

We can do that simply by using HostListener-Events. 我们只需使用HostListener-Events就可以做到这一点。 We can use it by importing it from @angular/core. 我们可以通过从@ angular / core导入它来使用它。

https://angular.io/api/core/HostListener https://angular.io/api/core/HostListener

check the above link for more details, we can use "window:offline" and "window:online" in the place of navigator.online funtion to raise events which automatically listens if there is an internet connection or not. 查看上面的链接了解更多详情,我们可以使用“window:offline”和“window:online”代替navigator.online功能来引发事件,如果有互联网连接则会自动监听。 Based on that we can attach the above events in the form of displaying the messages either in a toastr or in a dialog box or what so ever. 基于此,我们可以以在toastr或对话框中显示消息的形式附加上述事件,或者如此。

As an example: 举个例子:

import { Component, HostListener } from "@angular/core";
import { Subscription } from "rxjs";
import { Observable } from "rxjs/Observable";

@Component({

selector: 'app-online-offline',
templateUrl: './online-offline.component.html',
styleUrls: ['./online-offline.component.css']
})
export class OnlineOfflineComponent {
public isOnline: boolean;
public showConnectionStatus: boolean;
private showConnectionStatusSub: Subscription;
private showConnectionStatusTimer: Observable<any>;

constructor() {
    this.showConnectionStatusTimer = Observable.timer(5000);
}

@HostListener('window:offline', ['$event']) onOffline() {
    this.isOnline = false;
    this.showConnectionStatus = true;
    if (this.showConnectionStatusSub) {
        this.showConnectionStatusSub.unsubscribe();
    }
}

@HostListener('window:online', ['$event']) onOnline() {
    this.isOnline = true;
    this.showConnectionStatus = true;
    this.showConnectionStatusSub = this.showConnectionStatusTimer.subscribe(() => {
        this.showConnectionStatus = false;
        this.showConnectionStatusSub.unsubscribe();
        window.location.reload();
    });
}

ngOnDestroy(): void {
    if (this.showConnectionStatusSub) {
        this.showConnectionStatusSub.unsubscribe();
    }
}

} }

For Angular 2+ you can use ng-speed-test :对于 Angular 2+,您可以使用ng-speed-test

  1. Just install:只需安装:
npm install ng-speed-test --save
  1. Inject into your module:注入你的模块:
import { SpeedTestModule } from 'ng-speed-test';

@NgModule({
   ...
   imports: [
       SpeedTestModule,
       ...
   ],
   ...
})
export class AppModule {}
  1. Use service to get speed:使用服务获取速度:
import {SpeedTestService} from 'ng-speed-test';

@Injectable()
export class TechCheckService {
  constructor(
    private speedTestService:SpeedTestService
  ) {
    this.speedTestService.getMbps().subscribe(
      (speed) => {
        console.log('Your speed is ' + speed);
      }
    );
  }
}

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

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