How to check whether user has internet connection

2019-01-16 19:02发布

How I would check internet connection in Angular2 at the time of API hitting, whenever in my app API is hit to server sometimes user is offline (i mean without internet connection) so how would i check the internet connectivity ? is there some special status code for internet connectivity ? or something else ?

PS:- i found navigator.onLine in angularJs but seems not working in angular2.

update

as sudheer suggested in answer below navigator.onLine in working with angular2 but still not working properly why ? working example here

标签: http angular
7条回答
冷血范
2楼-- · 2019-01-16 19:29

As i have checked navigator is global object like window. You can use in in angular2 and it worked fine for me.

import {Component} from 'angular2/core';
@Component({
    selector: 'my-app',
    template:`
navigator.onLine
{{onlineFlag}}

`
})
export class AppComponent {
  public onlineFlag =navigator.onLine;
}
查看更多
太酷不给撩
3楼-- · 2019-01-16 19:31

Safe Approach to listen to network states

Answers given above works well but are not considered safe approach.

1.Browser dependent objects like window should not be referenced directly, always check for platform.

2.Furthermore functionality like Network Connection must be encapsulated into a service.

Below is the ConnectionService which can be subscribed to listen network states. It follows the rxjs 6 style.

Complete Code

import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { Observable, fromEvent, merge, empty } from 'rxjs';
import { isPlatformBrowser } from '@angular/common';
import { mapTo } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ConnectionService {

  private connectionMonitor: Observable<boolean>;

  constructor(@Inject(PLATFORM_ID) platform) {
if (isPlatformBrowser(platform)) {
  const offline$ = fromEvent(window, 'offline').pipe(mapTo(false));
  const online$ = fromEvent(window, 'online').pipe(mapTo(true));
  this.connectionMonitor = merge(
    offline$, online$
  );
} else {
  this.connectionMonitor = empty();
}



 }

  monitor(): Observable<boolean> {
    return this.connectionMonitor;
  }
}

in component, you may listen by subscribing to monitor() or directly into HTML using async pipe.

查看更多
老娘就宠你
4楼-- · 2019-01-16 19:34

Go with this simple Hack.

Working in angular 5 or later

 constructor(){
    setInterval(()=>{
       if(navigator.onLine){
         //here if it is online
       }else{
        //here if it is offline
       }
    }, 100)
 }

write this in constructor of app.component.ts or your app bootstrap No need of any external library ..

查看更多
Explosion°爆炸
5楼-- · 2019-01-16 19:47

(2018) Code updated for rxjs6

It totally works with angular2. Obviously it's different from angularJS because neither $scope nor $apply exist anymore. RxJS makes this easy, though! Tested on Chrome 53:

template:

<p>{{online$ | async}}</p>

component:

import { fromEvent, merge, of } from 'rxjs';
import { mapTo } from 'rxjs/operators';

@Component({ /* ... */ })
export class MyComponent {
  online$: Observable<boolean>;

  constructor() {
    this.online$ = merge(
      of(navigator.onLine),
      fromEvent(window, 'online').pipe(mapTo(true)),
      fromEvent(window, 'offline').pipe(mapTo(false))
    );
  }
}
查看更多
Anthone
6楼-- · 2019-01-16 19:47

Using Angular 6+ and Rxjs 6+, you can do it in the following way:

import { Observable, fromEvent, merge, of } from 'rxjs';
import { mapTo } from 'rxjs/operators';

online$: Observable<boolean>;

constructor() {
  this.online$ = merge(
    of(navigator.onLine),
    fromEvent(window, 'online').pipe(mapTo(true)),
    fromEvent(window, 'offline').pipe(mapTo(false))
  )
}

Here is a demo (toggle network in dev tools)

查看更多
Emotional °昔
7楼-- · 2019-01-16 19:47

Use this.

Without any external library.

public isOnline: boolean = navigator.onLine;

ngOnInit() { 
    console.log(this.isOnline); 
}
查看更多
登录 后发表回答