Skip to content

Instantly share code, notes, and snippets.

@sandy912
Created January 14, 2019 12:48
Show Gist options
  • Save sandy912/117d7dc25d29813e04e039624c10d113 to your computer and use it in GitHub Desktop.
Save sandy912/117d7dc25d29813e04e039624c10d113 to your computer and use it in GitHub Desktop.
[Ionic 4 network service] Just plug this service into your ionic app for checking the network connection inside the app or while starting the app #ionic #network #ionicnetwork
import { Injectable } from '@angular/core';
import { Network } from '@ionic-native/network/ngx'
import { BehaviorSubject, Observable } from 'rxjs';
import { ToastController, Platform } from '@ionic/angular';
export enum ConnectionStatus {
Online,
Offline
}
@Injectable({
providedIn: 'root'
})
export class NetworkService {
private status: BehaviorSubject<ConnectionStatus> = new BehaviorSubject(ConnectionStatus.Offline);
constructor(private network: Network, private toastController: ToastController, private plt: Platform) {
this.plt.ready().then(() => {
this.initializeNetworkEvents();
let status = this.network.type !== 'none' ? ConnectionStatus.Online : ConnectionStatus.Offline;
this.status.next(status);
});
}
public initializeNetworkEvents() {
this.network.onDisconnect().subscribe(() => {
if (this.status.getValue() === ConnectionStatus.Online) {
console.log('WE ARE OFFLINE');
this.updateNetworkStatus(ConnectionStatus.Offline);
}
});
this.network.onConnect().subscribe(() => {
if (this.status.getValue() === ConnectionStatus.Offline) {
console.log('WE ARE ONLINE');
this.updateNetworkStatus(ConnectionStatus.Online);
}
});
}
private async updateNetworkStatus(status: ConnectionStatus) {
this.status.next(status);
let connection = status == ConnectionStatus.Offline ? 'Offline' : 'Online';
let toast = this.toastController.create({
message: `You are now ${connection}`,
duration: 1500,
position: 'bottom',
mode: 'ios',
translucent: true
});
toast.then(toast => toast.present());
}
public onNetworkChange(): Observable<ConnectionStatus> {
return this.status.asObservable();
}
public getCurrentNetworkStatus(): ConnectionStatus {
return this.status.getValue();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment