简体   繁体   English

检测“在线”和“离线” angular 8

[英]Detection of "online" and "offline" angular 8

I have the following service for checking.network connection:我有以下检查网络连接的服务:

export class InternetService {
public connectionChanged = new BehaviorSubject<boolean>(false);
public connState =  true;
constructor(private apiService: ApiService) {
    if (navigator.onLine)
        this.statusChanged(true);
    else
        this.statusChanged(false);
    this.addEventListeners();
}
private addEventListeners() {
    window.addEventListener('online', () => this.statusChanged(true));
    window.addEventListener('offline', () => this.statusChanged(false));
}

testConnection() {
    this.apiService.callMyMethod().subscribe(res => {
        this.connected(true);
    }, error => {
        this.connected(false);
    });
}
statusChanged(connected: boolean) {
    if (connected) {
        this.testConnection();
    } else {
        this.connected(false);
    }
}
connected(data: boolean) {
    this.connState = data;
    this.connectionChanged.next(this.connState);
}
}

Code functions work well on Edge Browser, but not on Chrome.代码函数在 Edge 浏览器上运行良好,但在 Chrome 上运行不佳。 I understand there is a problem with Chrome according to the following reference:根据以下参考资料,我了解到 Chrome 存在问题:

https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine https://developer.mozilla.org/zh-CN/docs/Web/API/NavigatorOnLine/onLine

In Chrome and Safari, if the browser is not able to connect to a local area.network (LAN) or a router, it is offline;在Chrome和Safari中,如果浏览器无法连接到局域网(LAN)或路由器,则为离线; all other conditions return true.所有其他条件返回真。 So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the inte.net.因此,虽然您可以假设浏览器在返回 false 值时处于离线状态,但您不能假设返回 true 值就一定意味着浏览器可以访问 inte.net。 You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethe.net adapters that are always "connected."您可能会得到误报,例如在计算机运行虚拟化软件的情况下,该软件具有始终“连接”的虚拟 ethe.net 适配器。 Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.因此,如果你真的想确定浏览器的在线状态,你应该开发额外的检查手段。

Basically, on chrome:基本上,在 chrome 上:

(1) navigator.onLine always returns true; (1) navigator.onLine 总是返回true; (2) when I disconnected or reconnect WiFi, the two "onLine" or "offLine" events do not do anything. (2) 当我断开或重新连接 WiFi 时,两个“onLine”或“offLine”事件没有做任何事情。

Is there an alternative way to have events when the WiFi is disconnected or reconnected?当 WiFi 断开或重新连接时,是否有其他方法可以产生事件?

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