I have a controller that does an API call. When there’s no network it shows no connection. But when the network is reconnected I want it to start doing that API call. I’m not sure on how to do this.
I’m using the Ionic Native Network plugin -> https://ionicframework.com/docs/native/network
I put those functions in a global provider.
When I get disconnected/connected again I do get the console log notice like in that example but I’m not sure how to tell the controller to do that function at that time.
I currently have this.
import {Injectable} from '@angular/core';
import {App} from 'ionic-angular';
import { Network } from '@ionic-native/network';
@Injectable()
export class GlobalProvider {
connection: boolean = false;
constructor(public app: App, public network: Network) {
this.network.onConnect().subscribe(() => {
console.log('network connected!');
this.connection = true;
});
this.network.onDisconnect().subscribe(() => {
console.log('network was disconnected :-(');
this.connection = false;
});
}
isOnline() {
return navigator.onLine;
}
}
import {Component} from '@angular/core';
import {LoadingController, NavController} from 'ionic-angular';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
import {Network} from '@ionic-native/network';
// Routes
import {NewsDetail} from '../news/news-detail';
// Providers
import {GlobalProvider} from '../../providers/global';
@Component({
selector: 'page-news',
templateUrl: 'news.html'
})
export class News {
posts: object;
firstPost: object;
postHeaderURL: string;
today: number;
notification: object = {image: '', title: '', content: ''};
loader: any;
constructor(public navCtrl: NavController, public http: Http, public globalProvider: GlobalProvider, public loadingCtrl: LoadingController, public network: Network) {
if (globalProvider.isOnline() || globalProvider.connection == true) {
this.sendHTTPRequest(loadingCtrl, globalProvider);
} else {
this.notification = globalProvider.notification['internet'];
}
}
sendHTTPRequest(loadingCtrl, globalProvider) {
this.today = Date.now();
this.loader = loadingCtrl.create();
this.loader.present();
this.http.get('https://www.nec-nijmegen.nl/wp-json/wp/v2/posts?_embed').map(res => res.json()).subscribe(
data => {
for (let j = 0; j < data.length; j++) {
if (this.dateDiffInDays(data[j].date, this.today) == 0) {
data[j].today = true;
}
}
this.posts = data;
this.firstPost = data[0];
this.postHeaderURL = 'assets/img/header/Vooraanzicht_Goffertstadion_2HH.jpg';
},
err => {
this.notification = globalProvider.notification['internal'];
console.log('Error ' + err.status + ' | ' + JSON.parse(err._body).message);
},
() => {
this.loader.dismiss()
}
);
}
}