根据我的应用程序,每当用户与网络断开连接时,我都必须通知用户。所以在提供程序中,我使用了两个函数,一个在在线状态下返回 true,另一个在离线状态下返回 true。在 app.component.ts 中,通过调用提供者的“isOnline()”来检查应用是否处于在线状态。这里提供者代码..
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Network } from '@ionic-native/network';
import { Platform } from 'ionic-angular';
import {Observable} from 'rxjs/Rx';
/*
Generated class for the Connectivity provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
declare var Connection;
@Injectable()
export class Connectivity {
onDevice: boolean;
myObservable :any;
constructor(public http: Http,public platform: Platform,public network:Network) {
console.log('Hello Connectivity Provider');
this.onDevice = this.platform.is('cordova');
/*
this.myObservable = Observable.create(observer => {
let result = this.isOffline();
observer.next(result);
});
*/
}
isOnline(): boolean {
if(this.onDevice && this.network.type){
return this.network.type !== Connection.NONE;
} else {
return navigator.onLine;
}
}
isOffline(): boolean {
if(this.onDevice && this.network.type){
return this.network.type === Connection.NONE;
} else {
return !navigator.onLine;
}
}
}
在 app.component.ts 的构造函数中调用 isOnline()
constructor(platform: Platform,public connectivityService: Connectivity) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Splashscreen.hide();
/*this.connectivityService.myObservable.subscribe((data) => {
console.log(data);
});*/
if(this.connectivityService.isOnline()){
console.log("online");
}
else {
console.log("offline");
}
});
这工作正常但是,当我与网络断开连接时,我必须再次刷新浏览器,然后才能在控制台上看到“离线”。如何在网络丢失时立即通知用户