可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
- Source - How to check internet connection in AngularJs
update
as sudheer suggested in answer below navigator.onLine
in working with angular2 but still not working properly why ?
working example here
回答1:
(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))
);
}
}
回答2:
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() {
}
}
回答3:
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;
}
回答4:
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)
回答5:
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 ..
回答6:
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.
回答7:
Use this.
Without any external library.
public isOnline: boolean = navigator.onLine;
ngOnInit() {
console.log(this.isOnline);
}