Check internet connection in web using Angular 4

后端 未结 10 2125
感情败类
感情败类 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: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, next: HttpHandler): Observable> {
                // 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
        }
    

提交回复
热议问题