Согласно моему приложению, я должен уведомлять пользователя всякий раз, когда он отключается от сети. Поэтому в провайдере я использовал две функции: одна возвращает 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");
}
});
это работает нормально, но когда я отключаюсь от сети, мне нужно снова обновить браузер, тогда я могу видеть только "офлайн" на консоли. как уведомить пользователя, как только сеть потеряна