Some code first, this is from a small provider I created for data synchronization process,
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Subscription } from "rxjs/Rx";
import { Platform, AlertController } from "ionic-angular";
import { Network } from "@ionic-native/network";
import { Storage } from "@ionic/storage";
import { UnderDevelopment } from "../under-development";
import { ApiServicesProvider } from "../../providers/api-services/api-services";
import * as moment from "moment";
@Injectable()
export class DataSyncProvider {
connected: Subscription;
disconnected: Subscription;
constructor(
public plfm: Platform, public net: Network,
private undev: UnderDevelopment,
private storage: Storage,
private alertCtrl: AlertController,
private api: ApiServicesProvider) {
}
stop() {
this.connected.unsubscribe();
this.disconnected.unsubscribe();
}
setup() {
this.net.onchange().subscribe((...data) => {
console.log(JSON.stringify(data));
this.undev.addLater("What the heck...? " + this.net.type);
});
this.connected = this.net.onConnect()
.subscribe(result => {
console.log(JSON.stringify(result));
this.alertCtrl.create({
title: 'Available network',
message: 'Synchronize offline data before continuing using.',
buttons: [{
text: 'Sync',
handler: () => this.loadSchedules()
}]
});
});
this.disconnected = this.net.onDisconnect()
.subscribe(result => {
console.log(JSON.stringify(result));
this.alertCtrl.create({
title: 'Offine network',
message: 'Consecutive data changes will be saved offline.',
buttons: [{
text: 'Acknowledge',
handler: () => this.undev.addLater('Now storing data offline!')
}]
})
});
}
loadSchedules() {
var today = moment().format("YYYY-MM-DD");
this.undev.addLater(`Loading schedules today: ${today}`);
// TODO: real request here
// this.storage.set('db.synced', true);
}
}
As you can see, those two onConnect()
and onDisconnect()
work badly!
and I see lots of people struggle on this issue lately
(well, I didn’t add setTimeout(...)
like the API document suggests, just because it makes me wait like forever)
But unexpectedly, that onchange()
works great! It just gives right values at right time,
of course when network connection is truly available
so what you guys think?