我想通过完整的离子应用程序检查离线和在线模式,如何制作?

时间:2019-03-01 08:09:29

标签: angular typescript ionic-framework

我这里有一个错误。我也想在这段代码中通过完整的应用程序在线和离线进行扫描,而不仅仅是在启动时进行扫描。 app.component.ts文件:

constructor(platform: Platform, statusBar: StatusBar, modalCtrl: ModalController, private network: Network, private toast: ToastController) {
platform.ready().then(() => {

  this.network.onDisconnect().subscribe(() => {
    this.connOff();
  }
  );

  this.network.onConnect().subscribe(() => {
    this.connEst();
  }
  )

})

}


    connEst() {
        let toast = this.toast.create({
          message: 'Connection Established.',
          duration: 3000
        });
        toast.present();
      }
      connOff() {
        let toast = this.toast.create({
          message: 'Network OFFLINE.',
          duration: 3000
        });
        toast.present();
      }
    }

2 个答案:

答案 0 :(得分:0)

这是我的网络服务,也许您可​​以使用它与您的网络服务进行比较

If the exception is not caught, a 404 HTTP response is automatically sent back to the user

}

答案 1 :(得分:0)

app.module.ts

在您的提供商中添加服务

@NgModule({
...
providers: [NetworkService],
...
})

app.component.ts

infoConnection$ = this.networkService.infoConnection$;

constructor(private networkService: NetworkService) {
  this.networkService.infoConnection$.subscribe(infoConnection => {
    console.log(infoConnection)
  })
}

network.service.ts

import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { Network } from '@ionic-native/network';
import { Subject } from 'rxjs/Subject';
import { NotificationService } from './notification-service';

@Injectable()
export class NetworkService {

  info: any = {
    connected: true,
    type: "none"
  };

  disconnectSubscription: any;
  connectSubscription: any;

  private infoConnection = new Subject<any>();
  infoConnection$ = this.infoConnection.asObservable();

  constructor(
    private network: Network,
    private platform: Platform,
    private notificationService: NotificationService,
  ) {
    this.disconnectSubscription = this.network.onDisconnect().subscribe(() => {
      this.sendStatus();
    });

    this.connectSubscription = this.network.onConnect().subscribe(() => {
      this.sendStatus();
    });
  }

  sendStatus() {
    if (this.platform.is("cordova")) {
      setTimeout(() => {
        this.info = {
          connected : this.isConnected(),
          type: this.getConnectionType()
        }
        this.infoConnection.next(this.info);
      }, 3000);
    }
  }

  isConnected() {
    if (this.platform.is("cordova")) {
      let hasConnection = this.network.type == "none" || this.network.type == 'unknown' ? false : true;
      return hasConnection;
    } else {
      return true;
    }
  }

  getConnectionType() {
    if (this.platform.is("cordova")) {
      return this.network.type;
    } else {
      return true
    }
  }

尝试连接手机以进行测试