I am working with ionic v3 | v4 and I need to persist when my app has an internet connection. https://ionicframework.com/docs/native/network this solution does not work because when connecting to a wifi network but we do not have connection to the external network it continues to inform that it is connected.
import { Injectable , HostListener } from ‘@angular/core’;
import { Platform } from ‘@ionic/angular’;
import { BehaviorSubject, interval } from “rxjs”
import { HTTP } from ‘@ionic-native/http/ngx’;
const tcpie = require(‘tcpie’);
const pie = tcpie(‘google.com’, 443, { count: 10, interval: 6000, timeout: 2000 });
import { Plugins } from ‘@capacitor/core’;
import { Network } from ‘@ionic-native/network/ngx’;
// // const { Network } = Plugins;
// import { HttpClientModule } from ‘@angular/common/http’;
// import { HttpModule } from ‘@angular/http’;
// import { Http ,Response ,Headers, RequestOptions} from ‘@angular/http’;
import { HttpClient } from “@angular/common/http”;
import { first } from “rxjs/operators”;
import { Subscription } from ‘rxjs’;
import { map } from ‘rxjs/operators’
import { Diagnostic } from ‘@ionic-native/diagnostic/ngx’;
import * as firebase from ‘firebase’;
@Injectable({
providedIn: ‘root’
})
export class ConnectivityService {
onDevice: boolean;
public connected$ = new BehaviorSubject(false);
// private config = ‘http://economizeplus-app.firebaseio.com’;
private config: string = ‘https://economizeplus-app.firebaseio.com/’;
public connState: boolean;
private source = interval(6000);
private timeout
public isOnline: boolean;
public showConnectionStatus: boolean;
private showConnectionStatusSub: Subscription;
constructor(private http: HttpClient, public platform: Platform, private HTTPs: HTTP,
private network: Network,private diagnostic: Diagnostic) {
this.diagnostic.isNetworkLocationAvailable
console.log('network');
// this.network.onDisconnect().subscribe(() => {
// console.log('network was disconnected :-(');
// console.log('this.network', this.network);
// });
// this.network.onConnect().subscribe(() => {
// console.log('we got a this.network.type ', this.network.type );
// console.log(' this.network.Connection ', this.network.Connection );
// console.log(' this.network.downlinkMax ', this.network.downlinkMax );
// console.log('this.network', this.network);S
// })
// var connectedRef = firebase.database().ref(".info/connected");
// connectedRef.on("value", function (snap) {
// if (snap.val() === true) {
// console.log('network connected! ');
// } else {
// console.log('not connected! ');
// }
// });
// firebase.database().ref(".info/connected").on("value", data => {
// console.log('network ! ', data);
// });
firebase.database().ref('.info/connected').on('value', connectedSnap => {
if (connectedSnap.val() === true) {
console.log('network ! ', connectedSnap.val() );
} else {
console.log(' not network ! ', connectedSnap.val() );
}
});
this.source.subscribe(async () => {
// console.log('network check');
// this.http.get('www.google.com',{}).pipe(map((res: Response) =>{
// var data = res.json();
// console.log('network connected! ', res);
// }));
// this.http.get('www.google.com',{}).subscribe(data =>{
// console.log('network connected! ', data);
// })
// this.network.onConnect().subscribe(() => {
// console.log('network connected!');
// // We just got a connection but we need to wait briefly
// // before we determine the connection type. Might need to wait.
// // prior to doing any api requests as well.
// console.log('this.network.downlinkMax', this.network.downlinkMax);
// console.log('we got a wifi connection, woohoo!', this.network.type );
// });
// this.http.get('http://www.google.com.br', {}, {})
// .then(data => {
// console.log(data);
// console.log(data.status);
// console.log(data.data); // data received by server
// console.log(data.headers);
// })
// .catch(error => {
// console.log(error.status);
// console.log(error.error); // error message as string
// console.log(error.headers);
// });
// let handler = Network.addListener('networkStatusChange', (status) => {
// console.log("Network status changed", status);
// });
// // To stop listening:
// // handler.remove();
// // Get the current network status
// let status = await Network.getStatus();
// console.log("Network status status", status);
// pie.on('connect', function (stats) {
// console.info('connect', stats);
// }).on('error', function (err, stats) {
// console.error(err, stats);
// }).on('timeout', function (stats) {
// console.info('timeout', stats);
// }).on('end', function (stats) {
// console.info(stats);
// // -> {
// // -> sent: 10,
// // -> success: 10,
// // -> failed: 0,
// // -> target: { host: 'google.com', port: 443 }
// // -> }
// }).start();
// try {
// this._http.request()
// .pipe(first())
// .subscribe(resp => {
// console.log("ConnectivityService: resp", resp);
// if (resp.status === 200) {
// if (!this.connected$.value) {
// this.connected$.next(true);
// }
// }
// }, erro => {
// console.log("ConnectivityService erro: ", erro)
// if (this.connected$.value) {
// this.connected$.next(false);
// }
// })
// } catch (error) {
// console.log("ConnectivityService data: ", error)
// }
// });
// var xhr = new XMLHttpRequest();
// xhr.open("get", "https://www.google.com", true);
// xhr.getAllResponseHeaders
// xhr.onreadystatechange = function() {
// console.log('network connected! ', xhr);
// // if (xhr.readyState == 4) {
// // // JSON.parse does not evaluate the attacker's scripts.
// // var resp = JSON.parse(xhr.responseText);
// // }
// }
// xhr.send();
// try {
// this.http.get('http://www.google.com.br',CONNECT).pipe(first()).subscribe(data => {
// console.log('network data ', data);
// })
// } catch (error) {
// console.log('network erro ',error);
// }
// console.log('network this.network ',this.network);
// console.log('network this.network.downlinkMax) ',this.network.downlinkMax);
// console.log('network this.network.type ',this.network.type);
// console.log('network this.network.Connection ',this.network.Connection);
// let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
// console.log('network was disconnected :-(');
// });
// // stop disconnect watch
// disconnectSubscription.unsubscribe();
// // watch network for a connection
// let connectSubscription = this.network.onConnect().subscribe(() => {
// console.log('network connected!');
// // We just got a connection but we need to wait briefly
// // before we determine the connection type. Might need to wait.
// // prior to doing any api requests as well.
// setTimeout(() => {
// if (this.network.type === 'wifi') {
// console.log('we got a wifi connection, woohoo!');
// }
// }, 3000);
// });
// // stop connect watch
// connectSubscription.unsubscribe();
});
}
@HostListener(‘window:offline’, [’$event’]) onOffline() {
this.isOnline = false;
this.showConnectionStatus = true;
if (this.showConnectionStatusSub) {
this.showConnectionStatusSub.unsubscribe();
}
}
@HostListener(‘window:online’, [’$event’]) onOnline() {
this.isOnline = true;
this.showConnectionStatus = true
}
}