离子:检查设备是否已连接

时间:2018-12-20 13:18:42

标签: angular ionic-framework connection

我想在设备具有Internet连接时执行特定功能。

我尝试:

checkConnection(API){
  this.network.onConnect().subscribe(() => {
    this.changeAPI(API);
  });
  this.network.onDisconnect().subscribe(() =>{
    let loading = this.loadingCtrl.create({
      content: 'No Connection'
    });

    loading.present();

    setTimeout(() => {
      loading.dismiss();
    }, 1500);
  });
}

但是它不起作用,所以我如何检查连接?

1 个答案:

答案 0 :(得分:0)

对于此特定功能,我建议使用可观察的物体。另外,实施服务将使您可以检查整个应用程序中的连接。

//.ts

import { Injectable } from '@angular/core';
import { Network } from '@ionic-native/network';
import { Subscription } from 'rxjs/Subscription';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/interval';
 
Injectable()
export class DataService {
      connected: Subscription;
      disconnected: Subscription;
      public networkType:any;
      public online:any;
      constructor(  public network: Network){

          //May have to unsubscribe from Observable
        this.checkConnection = Observable.interval(250 * 60).subscribe(x => {
      //Check for connection every 15 seconds
          this.connected;
          this.disconnected;
          this.networkType = this.network.type;
          this.connected = this.network.onConnect().subscribe(data =>{
               this.online = data.type;
             }, error => console.error(error));

          this.network.onDisconnect().subscribe(data =>{
                this.online = data.type;
             },);
            }, error => console.error(error));
          }
        removeConnections(){
      this.checkConnection.unsubscribe();
      }
    }

在另一个页面中显示

import { Component } from '@angular/core';
import { IonicPage,NavParams} from 'ionic-angular';
import { DataService } from '../../services/dataservice';//service

@IonicPage()
@Component({
  selector: 'page-support',
  templateUrl: 'support.html',
})
export class SupportPage {
    constructor(private service: DataService){
    }
   }
//.html
<ion-header>
  <ion-navbar>
    <ion-title>Support</ion-title>
  </ion-navbar>
</ion-header>


<ion-content padding>
  <ion-grid>
     <ion-row>
        <ion-col>
          <h1>Connection: {{this.reap.networkType}}</h1>
        </ion-col>
      </ion-row>
  </ion-grid>
</ion-content>

观察者将不断检查您的连接,直到您取消订阅为止。因此,它也会在html代码中发生变化。