angular - IONIC 2 native Network.onDisconnect() running code twice -
i working ionic 2 rc1 , using sublime text editor. need check if network connection connected or not. purpose using ionic native network purpose. facing problem network.ondisconnect()
observable. have edited initializeapp()
method in check network connection , show alert if connection got disconnected. have following code written in app.component.ts
showalert(title, msg) { let alert = this.alertctrl.create({ title: title, subtitle: msg, buttons: ['ok'] }); alert.present(); } initializeapp() { this.platform.ready().then(() => { // okay, platform ready , our plugins available. // here can higher level native things might need. let disconnectsubscription = network.ondisconnect().subscribe(() => { this.showalert("error", "no internet connection"); }); statusbar.styledefault(); }); }
the problem facing alert shown twice if application disconnected internet. have found similar issue in post got unanswered. on regard appreciated. in advance !
in order avoid that, can filter events, , when state changes online offline, or offline online (and not every time event being fired plugin). can create service handle logic this:
import { injectable } '@angular/core'; import { network } 'ionic-native'; import { events } 'ionic-angular'; export enum connectionstatusenum { online, offline } @injectable() export class networkservice { private previousstatus; constructor(private eventctrl: events) { this.previousstatus = connectionstatusenum.online; } public initializenetworkevents(): void { network.ondisconnect().subscribe(() => { if (this.previousstatus === connectionstatusenum.online) { this.eventctrl.publish('network:offline'); } this.previousstatus = connectionstatusenum.offline; }); network.onconnect().subscribe(() => { if (this.previousstatus === connectionstatusenum.offline) { this.eventctrl.publish('network:online'); } this.previousstatus = connectionstatusenum.online; }); } }
so our custom events (network:offline
, network:online
) fired when connection changes (fixing scenario when multiple online or offline events fired plugin when connection state hasn't changed @ all).
then, in app.component
file need subscribe our custom events:
// offline event this.eventctrl.subscribe('network:offline', () => { // ... }); // online event this.eventctrl.subscribe('network:online', () => { // ... });
Comments
Post a Comment