2017-03-29 57 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顯示更改網絡狀態 –