0

我对 ionic 非常陌生,目前正在使用 Ionic 2 进行工作/学习。我想在用户下线时举杯祝酒。我目前能够做到这一点,如下面的代码所示(每当用户离线时都会显示吐司)。但是我想做的是在http请求上显示吐司(拉动刷新和无限滚动)。因此,即使数据已经加载,当用户尝试通过无限滚动刷新加载更多数据时,也会显示 toast,然后他们会收到离线通知。

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();
    }
}
4

1 回答 1

0

这就是我正在做的事情。在我的app.components我有连接订阅者,它离线或在线,所以如果用户离线我保存一个conn布尔变量为false,如果在线我在我的localStorage中保存true并展示一个吐司说它已经离线(如果在线有无需敬酒)。

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();
});

您可以创建一个服务来执行此操作,例如

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);
                }
            })
        })
    }
}

因此,在每个组件、页面输入、http 调用中,您导入该服务/提供程序并调用该verifyConnection函数,如果它返回 true,您只需让用户做它需要做的事情,如果它是 false,则提供程序将显示 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
    })
  }
}

希望能帮助到你 :)

于 2017-04-24T12:27:28.047 回答