@ ionic-native / network capture value from observable

I use @ ionic-native / network with the plug-plug-network-information plugin to check online offline status. However, it’s hard for me to update my network status.

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>

However, when the application starts, it shows only false, but console.log(this.online)shows true-false changes whenever I switch Wi-Fi. Any suggestions on how to change the interface values. View Chrome Inspect

+4
source share
2 answers

Try using ChangeDetectorRef if change detection does not occur in the template for any reason:

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
  });
}
+4
source
@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);
         });

     });

  }

}
+2

Source: https://habr.com/ru/post/1673498/


All Articles