In order to avoid that, you can filter the events, and just do something when the state changes from online to offline, or from offline to online (and not every time the event is being fired by the plugin). So basically you can create a service to handle all this logic like this:
import { Injectable } from '@angular/core';
import { Network } from 'ionic-native';
import { Events } from '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
and network:online
) will only be fired when the connection truly changes (fixing the scenario when multiple online or offline events are fired by the plugin when the connection state hasn't changed at all).
Then, in your app.component
file you just need to subscribe to our custom events:
// Offline event
this.eventCtrl.subscribe('network:offline', () => {
// ...
});
// Online event
this.eventCtrl.subscribe('network:online', () => {
// ...
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…