Manejo del Estado de Conexión a Internet en IONIC

I have worked as a frontend and backend developer handling technologies such as Django, Ionic, Laravel, MySQL, Spring (Java), Oracle, NodeJS, Angular, VueJS with the goal of developing websites and mobile applications that offer high performance and are interactive.
You can learn more about me by visiting my website: www.stalinmaza.com
#frontend #backend #fullstack #javascript #nodejs #php
En el transcurso del desarrollo de un proyecto que tengo, tuve la necesidad de tal como la hace Youtube poder mostrar un modal o una tarjeta que me indique que no tengo conexión a Internet y solo se muestre cuando tenga el internet apagado o si lo tengo encendido, solo se oculte cuando en realidad tengo conexión, para esto por ejemplo se haría una petición a alguna pagina web para comprobar en realidad que funciona la conexión.
Por lo que primeramente instalamos el plugin network de Cordova
ionic cordova plugin add cordova-plugin-network-information
npm install @ionic-native/network
Hecho esto para las necesidades que tengo me resulto mejor crear un servicio que me retorne un observable con el estado de la red, por lo que aplicamos el código inferior.
// Importar los Módulos Necesarios
import { Injectable } from '@angular/core';
import { Network } from '@ionic-native/network/ngx';
import { Platform } from '@ionic/angular';
import { Observable, fromEvent, merge, of, BehaviorSubject } from 'rxjs';
import { mapTo } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class NetworkService {
private online: Observable<boolean> = null;
private hasConnection = new BehaviorSubject(false);
constructor(
private network: Network,
private platform: Platform,
private http: HttpClient) {
if (this.platform.is('cordova')) {
// on Device
this.network.onConnect().subscribe(() => {
console.log('network was connected :-)');
this.hasConnection.next(true);
return;
});
this.network.onDisconnect().subscribe(() => {
console.log('network was disconnected :-(');
this.hasConnection.next(false);
return;
});
} else {
// on Browser
this.online = merge(
of(navigator.onLine),
fromEvent(window, 'online').pipe(mapTo(true)),
fromEvent(window, 'offline').pipe(mapTo(false))
);
this.online.subscribe((isOnline) =>{
if (isOnline) {
this.hasConnection.next(true);
console.log('network was connected :-)');
} else {
console.log('network was disconnected :-(');
this.hasConnection.next(false);
console.log(isOnline);
}
});
}
this.testNetworkConnection();
}
public getNetworkType(): string {
return this.network.type;
}
public getNetworkStatus(): Observable<boolean> {
return this.hasConnection.asObservable();
}
private getNetworkTestRequest(): Observable<any> {
return this.http.get('https://jsonplaceholder.typicode.com/todos/1');
}
public async testNetworkConnection() {
try {
this.getNetworkTestRequest().subscribe(
success => {
// console.log('Request to Google Test success', success);
this.hasConnection.next(true);
return;
}, error => {
// console.log('Request to Google Test fails', error);
this.hasConnection.next(false);
return;
});
} catch (err) {
console.log('err testNetworkConnection', err);
this.hasConnection.next(false);
return;
}
}
}
Ahora para obtener el estado de la conexión a internet solo debemos importar el servicio y subscribirnos al observable.
isConnected = false;
constructor(private networkService: NetworkService){
}
ngOnInit(){
this.networkService.getNetworkStatus().subscribe((connected: boolean) => {
this.isConnected = connected;
if (!this.isConnected) {
console.log('Por favor enciende tu conexión a Internet');
}
});
}

