Check internet connection in web using Angular 4

后端 未结 10 2089
感情败类
感情败类 2020-12-15 19:37

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 possib

相关标签:
10条回答
  • 2020-12-15 19:47

    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 these

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

    Add this method

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

    Subscribe to this event from your constructur or ngOnInit

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

    Note: Im using Angular 8.1 and rxjs 6.5.2

    0 讨论(0)
  • 2020-12-15 19:47

    I created a class called NetworkConnection which checks status of network connection. Here is code sample

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

    And you can use it like

    import { NetworkConnection, ConnectionStatusEnum } from './ConnectionStatus';
    ....
    if(NetworkConnection.status == ConnectionStatusEnum.Offline) {
        // do something
    }
    ....
    

    Additionally, if you want to check connection to internet, you can periodically ping sites like www.google.com instead of online/offline events. OR combination of both the approaches.

    0 讨论(0)
  • 2020-12-15 19:51

    For the required task, There is a npm package, ng-connection-service. Below is the complete code:

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

    Also you can find the working complete code over: click here

    0 讨论(0)
  • 2020-12-15 19:51
        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
        }
    
    0 讨论(0)
  • 2020-12-15 19:52

    A solution for RXJS 5.4.1 with Angular 4 based on @Dilshan Liyanage answer.

    import { Observable } from 'rxjs/Observable';
    import { fromEvent } from 'rxjs/observable/fromEvent';
    import { Observer } from 'rxjs/Observer';
    
       /**
       * Return an observable with a boolean based on internet connection status
       */
      public checkInternetConnection(): Observable<boolean> {
        return Observable.merge<boolean>(
          fromEvent(window, 'online').map(() => true),
          fromEvent(window, 'offline').map(() => false),
          new Observable((sub: Observer<boolean>) => {
            sub.next(navigator.onLine);
            sub.complete();
          })
        );
      }
    
    0 讨论(0)
  • 2020-12-15 20:00

    You do not have to use any library for this, you can handle this by this few lines of code.

    Add this below code into your comman error handler service file file name errors-handlers-services.ts

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

    This code block is working for me. maybe this code snippet helps you!!

    0 讨论(0)
提交回复
热议问题