2017-03-29 25 views
4

我使用@ ionic-native/network和cordova-plugin-network-information插件来检查在线 - 离线状态。然而,我很难更新网络状态。@离子本机/网络值从可观察到的

home.ts

import { Network } from '@ionic-native/network'; 

@Component({ 
    selector: 'page-home', 
    templateUrl: 'home.html' 
}) 
export class HomePage { 
public online:boolean=false; 
    constructor(public navCtrl: NavController,private network: Network) { 
     this.network.onDisconnect().subscribe(() => { 
     this.online=false; 
     console.log(this.online);  }); 
     this.network.onConnect().subscribe(() => { 
      this.online=true; 
     console.log(this.online); 
     }); 
    } 

} 

home.html的

<ion-header> 
    <ion-navbar> 
    <ion-title> 
     Ionic Blank 
    </ion-title> 
    </ion-navbar> 
</ion-header> 

<ion-content padding> 
    <h1>{{online}}</h1> 
</ion-content> 

然而上运行的应用,那只能说明假,然而console.log(this.online)显示每当我切换真假变化wifi。有关如何使界面值发生变化的任何建议。 Chrome Inspect output

回答

4

尝试使用ChangeDetectorRef,如果变化检测由于某种原因没有在模板发生:

import { ChangeDetectorRef } from '@angular/core'; 

constructor(private ref: ChangeDetectorRef) { } 

    this.network.onDisconnect().subscribe(() => { 
    this.online = false; 
    console.log(this.online); 
    this.ref.detectChanges(); // run  
    }); 
    this.network.onConnect().subscribe(() => { 
     this.online=true; 
     console.log(this.online); 
     this.ref.detectChanges(); // run 
    }); 
} 
+0

谢谢,它像一个魅力。 –

+0

太棒了!高兴听到! :) – Alex

+0

@ AJT_82很棒:) –

2
@Component({ 
    selector: 'page-home', 
    templateUrl: 'home.html' 
}) 
export class HomePage { 
public online:boolean=false; 
    constructor(public navCtrl: NavController,private network: Network) {} 

    ngOnInit(){ 
     this.network.onConnect().subscribe(() => { 
     this.online=true; 
     console.log(this.online); 

     this.network.onDisconnect().subscribe(() => { 
      this.online=false; 
      console.log(this.online); 
     }); 

    }); 

    } 

} 
+0

感谢repy但仍然接口值还没有改变console.log显示更改网络状态 –