My main goal here is to detect if the internet connection is active or not in my website.
The following line of codes is functional in my http://localhost:8100/
but unfortunately when I deployed my website in Heroku, all of this functions in detecting the internet connection failed.
This Ion Alert Controller detects if network connection is active or not. but unfortunately this alert doesn't respond in my system after the deployment. Alert Controller must be called if no connection was detected.
If user press the RELOAD, the whole page will reload again to check if connectivity exist:
This is the code for detecting network connectivity. I used this example: https://stackoverflow.com/a/57069101/13848366
app.component.ts
Note: I make createOnline$
Observable to detect automatically if the connection is change.
connectionMsg: boolean;
constructor(private alertController: AlertController) {
this.createOnline$().subscribe(isOnline => {
console.log(isOnline);
if (isOnline == true) {
this.connectionMsg = true;
} else {
this.connectionMsg = false;
this.reloadPage();
}
console.log("Msg: " + this.connectionMsg);
})
}
createOnline$() {
return merge<boolean>(
fromEvent(window, 'offline').pipe(map(() => false)),
fromEvent(window, 'online').pipe(map(() => true)),
new Observable((sub: Observer<boolean>) => {
sub.next(navigator.onLine);
sub.complete();
})
);
}
//THIS IS THE ION ALERT CONTROLLER WITH window.location.reload() to reload the whole page.
async reloadPage() {
const alert = await this.alertController.create({
header: 'Connection Lost',
message: 'Try to <strong>reload</strong> the page.',
backdropDismiss: false,
buttons: [
{
text: 'Reload',
handler: () => {
window.location.reload();
}
}
]
});
await alert.present();
}