【问题标题】:How to identify the internet status in ionic3如何在ionic3中识别互联网状态
【发布时间】:2017-11-29 04:34:51
【问题描述】:

我正在使用以下代码检查网络状态,但它仅在互联网像开关一样打开或关闭时才有效,但我想在加载页面时知道互联网的状态。

this.network.onConnect().subscribe(data => {
    console.log('Net status', data.type)
    if (data.type === 'online') {
      this.commonService.hideloader();
      console.log('data is online');
      const path = 'driver_user/vendor_allocations/bulk_create_update.json';
      const params = {'vendor_allocations': [save]};
      this._tokenService.post(path, params).map(res => res.json()).subscribe(
          res => {
            this.commonService.hideloader();
            console.log('res: ', res);
            this.sqliteService.update('entry', this.save_details, 'id', this.save_details.id).then(s => {
              console.log('Entry details saved in database', s);
              this.commonService.hideloader();
              this.commonService.presentToast('தகவல் சேமிக்கப்பட்டது');
              this.navCtrl.setRoot('FarmerlistPage');         
            });
          },
          error => {
            console.log(error);
            this.commonService.hideloader();
          }
      );           
    } else if (data.type !== 'online') {
      console.log('user seems to be offline');
      this.commonService.hideloader();
      this.commonService.presentToast('தகவல் சேமிக்கப்பட்டது');
    }
  }, error => console.error(error)); 

【问题讨论】:

    标签: cordova typescript ionic2 cordova-plugins ionic3


    【解决方案1】:

    您可以创建一个新方法并使用network.type 属性来检查:

    @Component({
      selector: 'home-page',
      templateUrl: 'home-page.html'
    })
    export class HomePage {
    
      constructor(private platform: Platform, private network: Network, //...) {}
    
      ionViewWillEnter() {
        this.platform.ready().then(() => {
          if(this.isOnline()) {
            // Code required to initialize the page if the user is online
          } else {
            // What to do when the user is offline
          }
        });
      }
    
      // Please notice that the type property will return one of the following 
      // connection types: `unknown`, `ethernet`, `wifi`, `2g`, `3g`, `4g`, 
      // `cellular`, `none`
    
      // Method that returns true if the user is connected to internet
      private isOnline(): boolean {
        return this.network.type.toLowerCase() !== 'none';
      }
    
      // Method that returns true if the user is not connected to internet
      private isOffline(): boolean {
        return this.network.type.toLowerCase() === 'none';
      }
    
    }
    

    【讨论】:

    • 我已经添加了更多的组件代码,如果有帮助请告诉我:)
    猜你喜欢
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多