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:48

At first, j2L4e's answer didn't work for me (testing in Chrome). I tweaked slightly by surrounding my bool in brackets in the ngIf and this ended up working.

<md-icon class="connected" mdTooltip="No Connection" *ngIf="!(isConnected | async)">signal_wifi_off</md-icon>

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/Rx';

@Component({
  selector: 'toolbar',
  templateUrl: './toolbar.component.html',
  styleUrls: ['./toolbar.component.css']
})
export class ToolbarComponent implements OnInit {
  isConnected: Observable<boolean>;

  constructor() {
    this.isConnected = Observable.merge(
      Observable.of(navigator.onLine),
      Observable.fromEvent(window, 'online').map(() => true),
      Observable.fromEvent(window, 'offline').map(() => false));
  }

  ngOnInit() {

  }
}
查看更多
登录 后发表回答