How to make my ion-refresher working properly when user goes offline and back to online?

Viewed 156

When i unplug my dsl cable and plug it again, my ion-refresher doesnt work properly i dunno why.

I want to stop it while internet is OFFLINE and when internet is ON user can do it.

Here's the code :

doRefresh(refresher) {
    if (this.isOnline) {
      this.refreshData();
      this.getAssignedWarrents()
        .then(() => {
          console.log('Refresher completed.');
          refresher.complete();
        });
       }else {
    refresher.complete();
    }
  }
2 Answers

A quick and dirty solution would be to directly use the navigator.onLine property instead of the isOnline property:

doRefresh(refresher) {
    if (navigator.onLine) {
        this.refreshData();
        this.getAssignedWarrents().then(
            () => {
                console.log('Refresher completed.');
                refresher.complete();
            }
        );
    } else {
        refresher.complete();
    }
}

Your current code does not work because you never update the isOnline property. So the refresher never 'knows' the internet connection went offline or online.

However, a better way to do this is to directly disable the ion-refresher in your view.

An example of how you could implement this.

<ion-refresher 
    [disabled]="hasNoInternetConnection()" 
    (ionRefresh)="doRefresh($event)">
</ion-refresher>

Next in your controller:

hasNoInternetConnection(): boolean {
    return !navigator.onLine;
}

doRefresh(refresher) {
    // Your usual refresh. Note how we do not need to check if we are online here.
    this.refreshData();
    this.getAssignedWarrents().then(
        () => {
            console.log('Refresher completed.');
            refresher.complete();
        }
    );
}

This approach is better because we let Ionic handle disabling the refresher instead of checking it ourselves.

If navigator.onLine is not working reliably for you you can also use the Network plugin provided by the Ionic team.

If we talk about Ionic environment, might be best way is to register handlers for Network like this:

  constructor(private network: Network) {}
  ...
  if (this.platform.is('cordova')) {
    this.network.onDisconnect().subscribe(
      async () => {
        await this.appOffline();
      },
      error => this.log.error('network.onDisconnect subscribe error: %j', error)
    );
    this.network.onConnect().subscribe(
      async () => {
        await this.appOnline();
      },
      error => this.log.error('network.onConnect subscribe error: %j', error)
    );
...

Related