使用 Angular 4 检查网络中的互联网连接 [英] Check internet connection in web using Angular 4

查看:37
本文介绍了使用 Angular 4 检查网络中的互联网连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Angular 4 进行应用程序开发.我需要检查网络连接是否可用,因为它使用 Angular 有任何连接问题.Angular 4 有可能吗.

I am using Angular 4 for my application development. I need to check If the network connection is available for its have any Connection issue using Angular for. Is it possible with Angular 4.

我检查了 https://github.com/HubSpot/offline .我认为这不适用于 angular 4.请任何人提出建议.这是否可以将 offlinejs 用于 Angular 4 或任何其他替代方案?

I checked with https://github.com/HubSpot/offline . I think this will not work for angular 4. Any one please suggest. Is this possible to use offlinejs for Angular 4 or any other alternatives?

谢谢莎拉 C M

推荐答案

我们不需要任何库,但是 public onlineOffline: boolean = navigator.onLine; 可以解决这个问题,但这是只是一次检查.我们需要将此值视为可观察的,因此每当在线状态发生变化时,我们都会更新.为此,rxjs 会有所帮助.

We don't need any libraries for this however public onlineOffline: boolean = navigator.onLine; will do the trick but this is just a one time check. We need to treat this value as an observable so whenever the online status change we are updated. For this rxjs will help.

导入这些

import { Observable, Observer, fromEvent, merge } from 'rxjs';
import { map } from 'rxjs/operators';

添加这个方法

  createOnline$() {
    return merge<boolean>(
      fromEvent(window, 'offline').pipe(map(() => false)),
      fromEvent(window, 'online').pipe(map(() => true)),
      new Observable((sub: Observer<boolean>) => {
        sub.next(navigator.onLine);
        sub.complete();
      }));
  }

从您的构造函数或 ngOnInit 订阅此事件

Subscribe to this event from your constructur or ngOnInit

this.createOnline$().subscribe(isOnline => console.log(isOnline));

注意:我使用的是 Angular 8.1rxjs 6.5.2

Note: Im using Angular 8.1 and rxjs 6.5.2

这篇关于使用 Angular 4 检查网络中的互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆