, , , - ,
, , . , plunker.
, ConnectivityService, - , ( ), ( - , -)
ConnectivityService.ts
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class ConnectivityService {
private connectionObserver: any;
public connection: any;
constructor(){
this.connectionObserver = null;
this.connection = Observable.create(observer => {
this.connectionObserver = observer;
});
}
public connectionHasChanged(private isOnline: bool) {
this.connectionObserver.next(isOnline);
}
}
"" "" ( , ), :
App.ts
import { Component } from "@angular/core";
import { ionicBootstrap, Platform } from 'ionic-angular/index';
import { HomePage } from './home.ts';
import { ConnectivityService } from 'connectivityService.ts';
@Component({
template: '<ion-nav [root]="rootPage"></ion-nav>',
providers: [ConnectivityService]
})
export class MyApp {
constructor(private platform: Platform, private connectivityService: ConnectivityService) {
this.addConnectivityListeners();
this.rootPage = HomePage;
}
// Subscribe to online/offline events
addConnectivityListeners(){
// Handle online event
document.addEventListener('online', () => {
// Call the service, to indicate now there connection (true)
this.connectivityService.connectionHasChanged(true);
}, false);
// Handle offline event
document.addEventListener('offline', () => {
// Call the service, to indicate now there no connection (false)
this.connectivityService.connectionHasChanged(false);
}, false);
}
}
ionicBootstrap(MyApp);
, : ( )
Home.ts
import { NavController } from 'ionic-angular/index';
import { Component } from "@angular/core";
import { ConnectivityService } from 'connectivityService.ts';
@Component({
templateUrl:"home.html"
})
export class HomePage {
public status: string = '';
constructor(private nav: NavController, private connectivityService: ConnectivityService) {
this.connectivityService.connection.subscribe((isOnline) => {
this.handleConnectionStatus(isOnline);
});
}
public handleConnectionStatus(private isOnline: bool) {
if(isOnline) {
this.status = 'Online';
console.log('Now is Online');
} else {
this.status = 'Offline';
console.log('Now is offline');
}
}
}