Last active
July 18, 2022 18:04
-
-
Save dvsingh9/4ef60c73f65e9742153c54f9df66fb94 to your computer and use it in GitHub Desktop.
Network Service for ionic - to identity android/iOS device is Offline/Online
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
const 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); | |
const connection = status === ConnectionStatus.Offline ? 'Offline' : 'Online'; | |
const toast = this.toastController.create({ | |
message: `You are now ${connection}`, | |
duration: 5000, | |
position: 'bottom', | |
color: 'primary', | |
animated: true | |
}); | |
toast.then(toast1 => toast1.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