Network Check and show Toast on Http Request

1k Views Asked by At

I am very new to ionic, currently working/learning with Ionic 2. I would like to show a toast when a user goes offline. I am currently able to do that as shown in my code below (toast shows whenever user goes offline). However what i would like to do is show the toast on http request (pull to refresh and infinite scroll). So that even when data is already loaded, the toast gets displayed when the user tries to pull to refresh on load more data through infinite scroll then they get notified that they are offline.

export class HomePage {
    datas:any = [];
    page:number =1;
    connected: Subscription;
    disconnected: Subscription;

    constructor(private toast: ToastController, private network: Network, public navCtrl: NavController, private wpapi: Wpapi) {
      this.getPosts();
    }

    displayNetworkUpdate(connectionState: string){
      //let networkType = this.network.type
      this.toast.create({
        message: `You are currently ${connectionState}, please re connect your data`,
        duration: 3000
      }).present();
    }

    ionViewDidEnter() {
          this.disconnected = this.network.onDisconnect().subscribe(data => {
            console.log(data)
            this.displayNetworkUpdate(data.type);
          }, error => console.error(error));
    }


    getPosts() {

        //this.page = '1';
        //this.wpapi.index(this.page)
        this.wpapi.index(1)
        .subscribe(data => {
          this.datas = data;
          console.log(this.datas);
        });
    }

    loadMore(infiniteScroll) {

        this.page++;

        this.wpapi.index( this.page ).subscribe( datas => {
          // Loads posts from WordPress API
          let length = datas["length"];

          if( length === 0 ) {
            infiniteScroll.complete();
            return;
          }

          for (var i = length - 1; i >= 0; i--) {
            this.datas.push( datas[i] );
          }

          infiniteScroll.complete();
        });
    }

    doRefresh(refresher) {
      this.wpapi.index(1)
        .subscribe(data => {
          this.datas = data;
        refresher.complete();
      });
    }

    ionViewWillLeave(){
      this.connected.unsubscribe();
      this.disconnected.unsubscribe();
    }
}
1

There are 1 best solutions below

0
On

This is what i'm doing. In my app.components i have the connection subscriber, beeing it offline or online, so if a user goes offline i save a conn boolean variable with false, if online i save true in my localStorage and present a toast saying it has gone offline (if gone online there's no need to present a toast).

network.onDisconnect().subscribe(() => {
    storage.set('conn', false);
    let conoff = ToastCtrl.create({
        closeButtonText: 'Ok',
        showCloseButton: true,
        message: 'You're not connected to internet.',
        position: 'top'
    });

    conoff.present();
});

You can create a service to do this, something like

import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import { ToastController, Platform } from 'ionic-angular';

@Injectable()
export class Verificador {

    constructor(public toast: ToastController, public storage: Storage, public platform: Platform) {
    }

    verifyConnection = (): Promise<boolean> => {
        return new Promise<boolean>((res, rej) => {
            this.storage.get('conn').then(conn => {
                if (conn) {
                    res(true);
                } else {
                    let t = this.toast.create({
                        closeButtonText: 'Ok',
                        showCloseButton: true,
                        message: 'You can't do this without internet.',
                        position: 'top'
                    });

                    t.present();
                    res(false);
                }
            })
        })
    }
}

So in every component, page entering, http call, you import that service/provider and call the verifyConnection function, if it returns true you just let the user do what it needs to do, if it's false the provider will show the toast.

import { ConnVerification} from '../../../providers/ConnVerification';

@IonicPage()
@Component({
    selector: 'your-page',
    templateUrl: 'your-page',
    providers: [ConnVerification]
})

export class YourPage {
  constructor(public verif: ConnVerification){}

  myFunctionForSomething(){
    this.verif.verifyConnection().then(conn =>{
      if(conn){
        // DO YOUR CODE
      }
      // NO NEED FOR ELSE SINCE IT'S HANDLED ON PROVIDER
    })
  }
}

Hope it helps :)