angular - native ionic 网络状态不适用于我的代码

标签 angular ionic-framework

我想在所有页面上没有连接和/或连接时显示警报消息,但它不起作用。显示网络类型有效,但没有显示任何警报消息。

目标是当APP连接和断开时显示消息。我正在关注https://ionicframework.com/docs/native/network/

这是我在 app.component.ts

中的代码
import { Component, ViewChild } from '@angular/core';
import { Nav, Platform, AlertController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { TranslateService } from '@ngx-translate/core';

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

import { ClientsListPage } from '../pages/clients/list';
import { JobsListPage } from '../pages/jobs/list';
import { SplashPage } from '../pages/splash/splash';
import { StatusPage } from '../pages/status/status';
import { LoginPage } from '../pages/login/login';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

  rootPage: any = SplashPage;
  pages: Array<{title: string, component: any}>;

  constructor(
    private translate: TranslateService,
    public platform: Platform,
    public network: Network,
    public statusBar: StatusBar,
    public splashScreen: SplashScreen,
    public storage: Storage,
    public alertCtrl: AlertController
  ) {
    this.initializeApp();
    this.initTranslate();

    // used for an example of ngFor and navigation
    this.pages = [
      { title: 'STATUS', component: StatusPage },
      { title: 'JOBS', component: JobsListPage },
      { title: 'CLIENTS', component: ClientsListPage }
    ];
  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.listenConnection();
    }).catch(error => console.log(JSON.stringify(error)))
  }

  initTranslate() {
    // Set the default language for translation strings, and the current language.
    this.translate.setDefaultLang('de');
  }

  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }

  logoutClicked() {
    let confirmation = this.alertCtrl.create({
      title: 'Sind Sie sicher?',
      message: 'Sind Sie sicher, dass Sie sich abmelden möchten? Alle nicht synchronisierten Daten gehen dadurch verloren.',
      buttons: [
        {
          text: 'Abbrechen',
          handler: () => {
            console.log('Disagree clicked');
          }
        },
        {
          text: 'Abmelden',
          handler: () => {
            this.storage.clear().then(
              () => this.nav.setRoot(LoginPage)
            )
          }
        }
      ]
    });

    confirmation.present();
  }

  private listenConnection(): void {
    console.log(JSON.stringify(this.network.type))
    let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
      let alert = this.alertCtrl.create({title: 'Connection', message: 'Network has been disconnected', buttons: ['OK']})
      alert.present()
    });

    disconnectSubscription.unsubscribe();

    let connectSubscription = this.network.onConnect().subscribe(() => {
      let alert = this.alertCtrl.create({title: 'Connection', message: 'Network has been connected', buttons: ['OK']})
      alert.present()
    })

    connectSubscription.unsubscribe();
  }
}

谢谢

最佳答案

以下是如何实现可在设备 (cordova) 和 pwa 模式下工作的“网络监视器”。在您的情况下,您取消了实际上应该保留的订阅。

  // DETECT DEVICE/BROWSER:
  this.appIsOnDevice = !this.platform.url().startsWith('http');

  // INIT NETWORK MONITOR:
  initNetworkMonitor() {
    // check if we are on device or if its a browser
    if (this.appIsOnDevice) {
      // watch network for a disconnect
      this.disconnectSubscription = this.network
        .onDisconnect()
        .subscribe(() => {
          console.log("network disconnected:(");
          // do alert here
        });
      // watch network for a connection
      this.connectSubscription = this.network.onConnect().subscribe(() => {
        console.log("network connected!");
        // app got back online, do logic here
        if (this.network.type === "wifi") {
          console.log("we got a wifi connection, woohoo!");
        }
      });
    } else {
      this.browserOffline = Observable.fromEvent(window, "offline").subscribe(
        () => {
          // go offline logic here
        }
      );
      this.browserOnline = Observable.fromEvent(window, "online").subscribe(
        () => {
          // go back online
        }
      );
    }
  }

关于angular - native ionic 网络状态不适用于我的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51395617/

相关文章:

java - 错误 : picked up java_options: -Djava.net.preferIPv4Stack=true

iOS 10 : CSS styles not being applied on class change

angular - 如何使用 tomcat 或应用程序服务器的环境变量以 Angular 配置基本 href?

html - 如何取消选中 Angular 7 中单击按钮时的复选框

node.js - Ionic2 Angular2 Typescript 模块 - 类型提示问题

angular - 找不到模块 : Error: Can't resolve '@angular/flex-layout' in '/app'

html - 如何在 Angular 中添加 bootstrap 5 模态

angular - 在 Ionic + Angular 中构建身份验证拦截器时出错

javascript - 我可以在网站上使用没有 ionic 的 ionic 组件吗?

cordova - 使用 ionic 框架从设备检索设备 token