首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >网络检查并在Http请求上显示Toast

网络检查并在Http请求上显示Toast
EN

Stack Overflow用户
提问于 2017-04-24 17:14:03
回答 1查看 860关注 0票数 0

我对ionic非常陌生,目前正在使用Ionic 2工作/学习。当用户离线时,我想表示敬酒。我目前可以这样做,如下面的代码所示(当用户离线时,toast就会显示)。然而,我想要做的是在http请求上显示toast (拉到刷新和无限滚动)。因此,即使数据已经加载,当用户尝试通过无限滚动拉动以刷新加载更多数据时,仍会显示toast,然后他们会收到离线通知。

代码语言:javascript
复制
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();
    }
}
EN

回答 1

Stack Overflow用户

发布于 2017-04-24 20:27:28

这就是我要做的。在我的app.components中,我有连接订阅者,无论它是离线还是在线,所以如果用户离线,我会用false保存一个conn布尔变量,如果在线,我会在localStorage中保存true,并提供一个吐司,说明它已经离线(如果在线,则不需要提供toast)。

代码语言:javascript
复制
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();
});

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

代码语言:javascript
复制
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,提供者将显示吐司。

代码语言:javascript
复制
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
    })
  }
}

希望它能有所帮助:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43584086

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档