【问题标题】:@ionic-native/network value capture from observable从可观察到的@ionic-native/network 值捕获
【发布时间】:2026-01-13 18:25:02
【问题描述】:

我正在使用带有 cordova-plugin-network-information 插件的@ionic-native/network 来检查在线-离线状态。但是我在更新网络状态时遇到了困难。

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>

但是在运行应用程序时,它只显示 false,但每当我切换 wifi 时,console.log(this.online) 会显示真假变化。关于如何使界面值更改的任何建议。

【问题讨论】:

    标签: angular ionic2 observable


    【解决方案1】:

    尝试使用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
      });
    }
    

    【讨论】:

    • 太棒了!高兴听到! :)
    • @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);
             });
    
         });
    
      }
    
    }
    

    【讨论】:

    • 感谢您的回复,但接口值仍然没有改变,console.log 显示正在更改网络状态
    最近更新 更多