One way to achieve this is by creating a network-state service:
network-state.service.ts
import { Injectable } from "@angular/core";
import { Network } from "@ionic-native/network/ngx";
import { Subscription } from "rxjs";
import { ShowToastService } from "./show-toast.service";
@Injectable({
providedIn: "root"
})
export class NetworkStateService {
private connectSubscription$: Subscription = null;
constructor(private network: Network,
private showToastService: ShowToastService) { }
WatchConnection() {
if (this.connectSubscription$) { this.connectSubscription$.unsubscribe(); }
this.connectSubscription$ = this.network.onDisconnect().subscribe(() => {
this.showToastService.showToast("Your internet seems to be down! Please check your network settings!",'danger');
if (this.connectSubscription$) { this.connectSubscription$.unsubscribe(); }
this.connectSubscription$ = this.network.onConnect().subscribe(() => {
setTimeout(async() => {
this.showToastService.toast.dismiss();
if (this.network.type === "wifi" || this.network.type === "4g" || this.network.type === "3g" || this.network.type === "2g" || this.network.type === "cellular" || this.network.type === "none") {
this.showToastService.showToast("Internet connection available!",'success');
this.WatchConnection();
}
}, 3000);
});
});
}
}
To use the service, inject it as shown below:
app.component.ts
constructor(private networkStateService: NetworkStateService,){
this.initializeApp();
}
async initializeApp() {
await this.platform.ready();
this.statusBar.styleDefault();
this.splashScreen.hide();
if (this.platform.is("cordova")) {
this.networkStateService.WatchConnection();
}
}
The showToast service looks like this:
show-toast.service.ts
import { Injectable } from "@angular/core";
import { ToastController, Events } from "@ionic/angular";
@Injectable({
providedIn: "root"
})
export class ShowToastService {
toast: HTMLIonToastElement;
constructor(private toastCtrl: ToastController,
) { }
async showToast(message: string, color: string): Promise<void> {
const toast: HTMLIonToastElement = await this.toastCtrl.create({
message,
duration: 3000,
position: 'bottom',
color,
buttons: [
{
text: 'Ok',
handler: () => {
}
}
]
});
toast.present();
}
}