问题描述
我正在使用Angular 4进行应用程序开发.我需要检查使用Angular的网络连接是否可用. Angular 4有可能吗?
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 possible with Angular 4.
我用https://github.com/HubSpot/offline
检查过.我认为这不适用于角度为4的任何人.请提出任何建议.可以将Offlinejs用于Angular 4或任何其他替代方法吗?
I checked with https://github.com/HubSpot/offline
. I think this will not work for angular 4. Any one please suggest. Is this possible to use offlinejs for Angular 4 or any other alternatives?
谢谢萨拉斯(Sarath)C M
ThanksSarath C M
推荐答案
我们不需要任何库,但是public onlineOffline: boolean = navigator.onLine;
可以解决问题,但这只是一次检查.我们需要将此值视为可观察的值,因此,每当在线状态发生变化时,我们都会进行更新.为此,rxjs会有所帮助.
We don't need any libraries for this however public onlineOffline: boolean = navigator.onLine;
will do the trick but this is just a one time check. We need to treat this value as an observable so whenever the online status change we are updated. For this rxjs will help.
导入这些
import { Observable, Observer, fromEvent, merge } from 'rxjs';
import { map } from 'rxjs/operators';
添加此方法
createOnline$() {
return merge<boolean>(
fromEvent(window, 'offline').pipe(map(() => false)),
fromEvent(window, 'online').pipe(map(() => true)),
new Observable((sub: Observer<boolean>) => {
sub.next(navigator.onLine);
sub.complete();
}));
}
通过您的构造函数或ngOnInit订阅此事件
Subscribe to this event from your constructur or ngOnInit
this.createOnline$().subscribe(isOnline => console.log(isOnline));
注意:我正在使用 Angular 8.1 和 rxjs 6.5.2
Note: Im using Angular 8.1 and rxjs 6.5.2
这篇关于使用Angular 4检查Web中的互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!