简体   繁体   中英

Ionic native network plugin

I need to check internet and id connection exist I need to perform a server request. I used ionic native network Plugin. But i done as per their official doc.

my CODE:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, LoadingController } from 'ionic-angular';
import { Auth } from '../../providers/auth/auth';
import { Network } from '@ionic-native/network';
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  constructor(private network: Network,private alertCtrl: AlertController,public navCtrl: NavController, public navParams: NavParams,public authService: Auth, public loadingCtrl: LoadingController) {

}
  ionViewDidLoad() {
      // watch network for a disconnect
    let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
        console.log('network was disconnected :-(');
    });
  disconnectSubscription.unsubscribe();
  // watch network for a connection
  let connectSubscription = this.network.onConnect().subscribe(() => {
    console.log('network connected!');
    //Check if already authenticated
    this.authService.checkAuthentication().then((res) => {
        console.log("Already authorized");
        this.loading.dismiss();
        this.navCtrl.setRoot(HomePage);
    }, (err) => {
        console.log("Not already authorized");
        this.loading.dismiss();
    });
  });

  // stop connect watch
  connectSubscription.unsubscribe();
    console.log('ionViewDidLoad LoginPage');
  }
}

My console shows this error:

在此处输入图片说明

Why does this happen? Is it necessary to add in providers array?

UPDATE

As Daniel B mentioned i added Network in providers array and the above error is gone. Now it didn't get inside this.network.onConnect()

您必须将Network添加到*.module.tsapp.module.ts )中的providers数组中。

You need to add Network as a provider.

To do this your app.module.ts add Network as a provider:

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

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    ...
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    Network
  ]
})

However, as the Network module is part of ionic-native it requires Cordova and therefore won't run in a browser, only in an emulator or natively.

I suggest wrapping the functions using the Network provider platform ready so it doesn't crash the browser but still works when there is cordova:

this.platform.ready().then(() => {
    // calls to ionic-native modules e.g. `Network` methods
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM