mirror of
https://code.equilibrium.co.ao/ITO/doneit-web.git
synced 2026-04-18 20:47:54 +00:00
67 lines
1.8 KiB
TypeScript
67 lines
1.8 KiB
TypeScript
import { Injectable } from '@angular/core';
|
|
import { ToastController, Platform } from '@ionic/angular';
|
|
import { BehaviorSubject, Observable } from 'rxjs';
|
|
import { Network } from '@ionic-native/network/ngx'
|
|
|
|
|
|
export enum ConnectionStatus {
|
|
Online,
|
|
Offline
|
|
}
|
|
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class NetworkServiceService {
|
|
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);
|
|
});
|
|
|
|
this.onNetworkChange().subscribe((status) => {
|
|
|
|
})
|
|
|
|
}
|
|
|
|
public initializeNetworkEvents() {
|
|
|
|
this.network.onDisconnect().subscribe(() => {
|
|
if (this.status.getValue() === ConnectionStatus.Online) {
|
|
this.updateNetworkStatus(ConnectionStatus.Offline);
|
|
}
|
|
});
|
|
|
|
this.network.onConnect().subscribe(() => {
|
|
if (this.status.getValue() === ConnectionStatus.Offline) {
|
|
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: 3000,
|
|
position: 'bottom'
|
|
});
|
|
toast.then(toast => toast.present());
|
|
}
|
|
|
|
public onNetworkChange(): Observable<ConnectionStatus> {
|
|
return this.status.asObservable();
|
|
}
|
|
|
|
public getCurrentNetworkStatus(): ConnectionStatus {
|
|
return this.status.getValue();
|
|
}
|
|
}
|