使用 Angular 4 检查网络中的互联网连接
我使用 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
.我认为这不适用于 angular 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?
谢谢莎拉 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