如何在ionic4中使用network.onDisconnect

时间:2019-07-06 12:46:17

标签: networking angular7 ionic4

我在代码使用网络中使用离子4

我的项目中的network.onDisconnect()无法正常工作

我要添加导入

ionic cordova plugin add cordova-plugin-network-information

npm install @ionic-native/network@5.9.0

无效代码:

this.network.onDisconnect().subscribe(() => {
  console.log('network was disconnected :-(');
  alert("FirstPage onDisconnect");
},
(error) => {
  alert(error);
});
this.network.onConnect().subscribe(() => {
  console.log('network was connected :-)');
  alert("FirstPage onConnect");
},
(error) => {
  alert(error);
});

或代码:

this.network.onDisconnect().subscribe(() => {
  console.log('network was disconnected :-(');
  alert("FirstPage onDisconnect");
});
this.network.onConnect().subscribe(() => {
  console.log('network was connected :-)');
  alert("FirstPage onConnect");
});

或代码:

  this.platform.ready().then(() => {
   this.network.onDisconnect().subscribe(() => {
    console.log('network was disconnected :-(');
    alert("FirstPage onDisconnect");
   });
   this.network.onConnect().subscribe(() => {
    console.log('network was connected :-)');
    alert("FirstPage onConnect");
   });
  });

或代码:

 window.addEventListener('online', function() {
   alert("ONLINE");
 }, false);

 window.addEventListener('offline', function() {
   alert("OFFLINE");
 }, false);

或代码:

document.addEventListener('online', function() {
  alert("ONLINE");
}, false);

document.addEventListener('offline', function() {
  alert("OFFLINE");
}, false);

离子信息:

 Ionic:

   ionic (Ionic CLI)             : 4.12.0 
   Ionic Framework               : @ionic/angular 4.5.0
   @angular-devkit/build-angular : 0.13.9
   @angular-devkit/schematics    : 7.3.9
   @angular/cli                  : 7.3.9
   @ionic/angular-toolkit        : 1.5.1

 Cordova:

   cordova (Cordova CLI) : 8.1.2 (cordova-lib@8.1.1)
   Cordova Platforms     : android 7.1.4, browser 5.0.4
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova- 
   plugin-ionic-webview 4.1.0, (and 10 other plugins)

 System:

   NodeJS : v10.12.0 (C:\Program Files\nodejs\node.exe)
   npm    : 6.4.1
   OS     : Windows 10

甚至从'@ ionic-native / network / ngx'添加导入{Network};在app.module.ts中 添加提供商网络

如何在我的项目中使用this.network.onDisconnect()和this.network.onConnect()?

谢谢

1 个答案:

答案 0 :(得分:1)

这是正确的代码:

  this.platform.ready().then(() => {
   this.network.onDisconnect().subscribe(() => {
    console.log('network was disconnected :-(');
    alert("FirstPage onDisconnect");
   });
   this.network.onConnect().subscribe(() => {
    console.log('network was connected :-)');
    alert("FirstPage onConnect");
   });
  });

它应该在构造函数中运行,您在哪里称呼它?

为什么还要专门针对该插件的v5.9.0?

我只会用:

npm install @ionic-native/network