使用Angular 4检查web中的internet连接

使用Angular 4检查web中的internet连接,angular,web,Angular,Web,我使用Angular 4进行应用程序开发。我需要检查网络连接是否可用,如果使用Angular for有任何连接问题。有没有可能用角4 我用https://github.com/HubSpot/offline。我认为这对angular 4不起作用。任何一个请推荐。对于Angular 4或任何其他备选方案,是否可以使用offlinejs 谢谢 Sarath C M您不必为此使用任何库,您可以使用navigator全局对象类窗口。你可以在angular4中使用 public onlineOffline

我使用Angular 4进行应用程序开发。我需要检查网络连接是否可用,如果使用Angular for有任何连接问题。有没有可能用角4

我用
https://github.com/HubSpot/offline
。我认为这对angular 4不起作用。任何一个请推荐。对于Angular 4或任何其他备选方案,是否可以使用offlinejs

谢谢
Sarath C M

您不必为此使用任何库,您可以使用
navigator
全局对象类窗口。你可以在angular4中使用

public onlineOffline: boolean = navigator.onLine;

我创建了一个名为
NetworkConnection
的类,用于检查网络连接的状态。下面是代码示例

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';

export enum ConnectionStatusEnum {
  Online,
  Offline
}

export class NetworkConnection {

  public static status: ConnectionStatusEnum = ConnectionStatusEnum.Online;
  private static online$: Observable<string>;
  private static offline$: Observable<string>;

  public static init() {
    NetworkConnection.online$ = Observable.fromEvent(window, 'online');
    NetworkConnection.offline$ = Observable.fromEvent(window, 'offline');

    NetworkConnection.online$.subscribe(e => {
      console.log('Online');
      NetworkConnection.status = ConnectionStatusEnum.Online;
    });

    NetworkConnection.offline$.subscribe(e => {
      console.log('Offline');
      NetworkConnection.status = ConnectionStatusEnum.Offline;
    });
  }

  constructor() {
    NetworkConnection.init();
  }

}

new NetworkConnection();

此外,如果你想检查互联网连接,你可以定期ping网站,比如
www.google.com
,而不是
online/offline
事件。或者两者的结合

对于所需的任务,有一个npm包,即ng连接服务。以下是完整的代码:

import { Component,OnInit } from '@angular/core';
import { ConnectionService } from 'ng-connection-service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'internet-connection-check';
  status = 'ONLINE'; //initializing as online by default
  isConnected = true;

  constructor(private connectionService:ConnectionService){
    this.connectionService.monitor().subscribe(isConnected => {
      this.isConnected = isConnected;
      if(this.isConnected){
        this.status = "ONLINE";
      } else {
        this.status = "OFFLINE"
      }
      alert(this.status);
    });
  }
  ngOnInit(){

  }

}
此外,您还可以在以下位置找到完整的工作代码:


navigator.onLine-->返回true或false

我们不需要任何库,但是
public onLine offline:boolean=navigator.onLine将完成此操作,但这只是一次检查。我们需要将该值视为一个可观察值,因此每当在线状态发生变化时,我们都会进行更新。对于这一点,rxjs将有所帮助

进口这些

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();
      }));
  }

注意:我使用的是Angular 8.1和rxjs 6.5.2,你不必使用任何库,你可以通过这几行代码来处理

将以下代码添加到comman错误处理程序服务文件中 文件名errors-handlers-services.ts

if (string.includes(<<error message>>)) {
      window.location.reload();
 }
if(string.includes()){
window.location.reload();
}

这个代码块对我有用。也许这段代码对你有帮助

可以通过
navigator.online
问题是,如果
navigator.onLine
返回false,则表示您处于脱机状态。但是,返回true并不能100%确保您在线。原因很简单,那就是浏览器的实现

从官方文档链接

浏览器以不同的方式实现此属性

在Chrome和Safari中,如果浏览器无法连接到本地 局域网(LAN)或路由器,它处于脱机状态;所有其他条件 返回true。因此,虽然您可以假设浏览器在 它返回一个假值,您不能假定它是真值 必然意味着浏览器可以访问internet。你可以 可能会出现误报,例如在计算机故障的情况下 运行具有虚拟以太网适配器的虚拟化软件 所以,如果你真的想 确定浏览器的联机状态时,应开发 检查的附加方法

在Firefox和Internet Explorer中,将浏览器切换为脱机 模式发送一个假值。在Firefox 41之前,所有其他条件 返回一个真实值;在Windows上测试夜间68的实际行为 显示它只寻找像Chrome和Safari这样的局域网连接 给出假阳性


基于@Dilshan Liyanage答案的角度为4的RXJS 5.4.1的解决方案

从'rxjs/Observable'导入{Observable};
从'rxjs/observable/fromEvent'导入{fromEvent};
从'rxjs/Observer'导入{Observer};
/**
*根据internet连接状态返回一个带有布尔值的可观察值
*/
public checkInternetConnection():可观察{
返回可观察。合并(
fromEvent(窗口“联机”).map(()=>true),
fromEvent(窗口“脱机”).map(()=>false),
新可观察((子:观察者)=>{
sub.next(navigator.onLine);
sub.complete();
})
);
}
从'@angular/core'导入{Injectable};
进口{
HttpRequest,
HttpHandler,
HttpEvent,
http拦截器
}来自“@angular/common/http”;
从“rxjs/Observable”导入{Observable};
@可注射()
导出类InternetInterceptor实现HttpInterceptor{
构造函数(){}
拦截(请求:HttpRequest,下一步:HttpHandler):可观察{
//检查一下是否有互联网
如果(!window.navigator.onLine){
//如果没有internet,抛出HttpErrorResponse错误
//由于抛出错误,函数将在此处终止
返回Observable.throw(新的HttpErrorResponse({error:'需要Internet.'}));
}否则{
//否则返回正常请求
下一步返回。处理(请求);
}
}
}
并将其放入app.module.ts的提供者中
{
提供:HTTP_拦截器,
使用类别:InternetInterceptorService,
多:真的
}

检测角度应用程序中的internet连接状态

我们可以使用
window.ononOnline
window.onoffline
事件来实现所需的特性

您可以通过
npm
命令安装服务:

npm i ng-connection-service
Subscribe to monitor()方法,以便在更改internet连接状态时获取推送通知

import { Component } from '@angular/core';
import { ConnectionService } from 'ng-connection-service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  status = 'ONLINE';
  isConnected = true;

  constructor(private connectionService: ConnectionService) {
    this.connectionService.monitor().subscribe(isConnected => {
      this.isConnected = isConnected;
      if (this.isConnected) {
        this.status = "ONLINE";
      }
      else {
        this.status = "OFFLINE";
      }
    })
  }
}

它的可能副本将在每次页面加载时检查是否正确?。没有页面刷新,如果连接断开,我需要通知用户。而其重新连接也需要通知。我怎么能这样做?它总是回来的True@Sajeetharan我使用的代码与答案中发布的代码相同,但它总是返回true。为什么?@PrashantPimpale检查我的答案。@Dilshanli Yanage okaynice解决方案!爱死它了!在Angular 8.2.14和rxjs 6.5.3中工作良好我爱你!现在我知道怎么做var观测了,谢谢在安格尔工作的布朗特
if (string.includes(<<error message>>)) {
      window.location.reload();
 }
    import { Injectable } from '@angular/core';
    import {
        HttpRequest,
        HttpHandler,
        HttpEvent,
        HttpInterceptor
    } from '@angular/common/http';
    import { Observable } from 'rxjs/Observable';
    
    @Injectable()
    export class InternetInterceptor implements HttpInterceptor {
        constructor() { }
    
        intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            // check to see if there's internet
            if (!window.navigator.onLine) {
                // if there is no internet, throw a HttpErrorResponse error
                // since an error is thrown, the function will terminate here
                return Observable.throw(new HttpErrorResponse({ error: 'Internet is required.' }));
    
            } else {
                // else return the normal request
                return next.handle(request);
            }
        }
    }


and put this in providers of app.module.ts
{
        provide: HTTP_INTERCEPTORS,
        useClass: InternetInterceptorService,
        multi: true
    }
npm i ng-connection-service
import { Component } from '@angular/core';
import { ConnectionService } from 'ng-connection-service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  status = 'ONLINE';
  isConnected = true;

  constructor(private connectionService: ConnectionService) {
    this.connectionService.monitor().subscribe(isConnected => {
      this.isConnected = isConnected;
      if (this.isConnected) {
        this.status = "ONLINE";
      }
      else {
        this.status = "OFFLINE";
      }
    })
  }
}