这是检查应用程序是在线还是离线的代码:
this.online$ = Observable.merge(
Observable.of(navigator.onLine),
Observable.fromEvent(window, 'online').map(() => true),
Observable.fromEvent(window, 'offline').map(() => false)
)
this.online$.subscribe(isOnline=>{
if(isOnline){
console.log(isOnline);
}else{
console.log("you are offline");
console.log(isOnline);
}
});
但它总是返回真实,这意味着它们在线,但结果却是错误的。我关闭系统互联网不太可能返回相同的结果(真实)。
答案 0 :(得分:5)
import { fromEvent, merge, of } from 'rxjs';
import { mapTo } from 'rxjs/operators';
this.online$ = merge(
of(navigator.onLine),
fromEvent(window, 'online').pipe(mapTo(true)),
fromEvent(window, 'offline').pipe(mapTo(false))
);
this.online$.subscribe((isOnline) =>{
if(isOnline) {
console.log(isOnline);
} else {
console.log("you are offline");
console.log(isOnline);
}
});
根据浏览器的在线状态,这会发出 true 或 false 。
答案 1 :(得分:0)
我的应用中有以下代码:
// Adjust the imports if you use RxJS < 6.0.0-alpha.3.
import { BehaviorSubject, fromEvent } from 'rxjs';
/**
* Whether the browser indicates that the device is online.
*/
export const onlineSubject = new BehaviorSubject<boolean>(true);
const handleOnlineChange = (online: boolean) => {
if (online !== onlineSubject.getValue()) {
onlineSubject.next(online);
}
};
handleOnlineChange(navigator.onLine);
fromEvent(window, 'online').subscribe(() => handleOnlineChange(true));
fromEvent(window, 'offline').subscribe(() => handleOnlineChange(false));
希望这对你有用。
答案 2 :(得分:0)
最轻的版本,始终返回navigator.onLine
值:
import { fromEvent, merge, of } from 'rxjs';
import { map } from 'rxjs/operators';
isOffline$ = merge(
of(null),
fromEvent(window, 'online'),
fromEvent(window, 'offline')
).pipe(map(() => !navigator.onLine));