简体   繁体   English

Cordova网络信息插件中未定义连接

[英]Connection is not defined in cordova network information plugin

I have followed this article: 我跟着这篇文章:

to get network information of the device in ionic app for android. 获取 android的离子应用程序中的设备的网络信息

It works fine on browser but when I install the compiled apk in android phone, it gives an error that says Reference error : Connection is not defined. 它在浏览器上工作正常但是当我在android手机中安装编译的apk时,它会出现错误,指出Reference error : Connection is not defined. at line where I use $cordovaNetwork.isOnline(); 在我使用$cordovaNetwork.isOnline();

I have been banging my head around and have done my due research and tried uninstalling and installing it in the order suggested but no help. 我一直在摸不着头脑,做了我应有的研究,尝试按照建议的顺序卸载和安装,但没有帮助。

Help me fix this issue. 帮我解决这个问题。 This problem is probably not an issue with code and may be need some clever fix to get it working. 这个问题可能不是代码的问题,可能需要一些聪明的修复才能使其正常工作。

This same issue is being discussed here but I have not really understood where is that given piece of code coming from. 这里正在讨论同样的问题但我还没有真正理解给定的代码来自何处。

index.html : index.html:

<!DOCTYPE html>
<html ng-app="starter" >
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">

    <title></title>
    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
  <!--   <link href="lib/ionic/css/angular-datepicker.min.css" rel="stylesheet"> -->
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->
    <!-- angular date picker css-->
    <link href="lib/datePicker/css/angular-pickadate.css" rel="stylesheet">

    <script src="lib/ionic/js/ionic.bundle.js"></script>
    <script src="lib/ionic/js/highcharts-ng.js"></script>
    <script src="lib/ionic/js/jquery.min.js"></script>
    <script src="lib/ionic/js/highcharts.js"></script>
     <script src="lib/ionic/js/ngStorage.min.js"></script>
    <script src="lib/ngCordova/dist/ng-cordova.min.js"></script>



    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>
    <!-- your app's js -->
    <script src="js/app.js"></script>
       <script src="js/controllers.js"></script>





  </head>
  <body ng-controller="LoginCtrl">

     <ion-nav-bar class="mob-bar-balanced">
     <!--  <ion-nav-back-button>
      </ion-nav-back-button> -->
    </ion-nav-bar>
    <ion-nav-view></ion-nav-view>
  </body>
</html>

app.js: app.js:

app.factory('ConnectivityMonitor', ['$rootScope', '$cordovaNetwork', function($rootScope, $cordovaNetwork){
  return {
    isOnline: function(){
      if(ionic.Platform.isWebView()){
       $rootScope.online = $cordovaNetwork.isOnline();
        return $cordovaNetwork.isOnline();    
      } else {
        $rootScope.online = navigator.onLine;
        return navigator.onLine;
      }
    },
    isOffline: function(){
      if(ionic.Platform.isWebView()){
        $rootScope.online = $cordovaNetwork.isOnline();   
        return !$cordovaNetwork.isOnline();    
      } else {
        $rootScope.online = navigator.onLine;
        return !navigator.onLine;
      }
    },
    startWatching: function(){
        if(ionic.Platform.isWebView()){

          $rootScope.$on('$cordovaNetwork:online', function(event, networkState){
            $rootScope.online =true;
            console.log("went online");
          });

          $rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
             $rootScope.online =false;
            console.log("went offline");
          });

        }
        else {

          window.addEventListener("online", function(e) {
            $rootScope.online =true;
            console.log("went online");
          }, false);    

          window.addEventListener("offline", function(e) {
            $rootScope.online =false;
            console.log("went offline");
          }, false);  
        }       
    }
  }
}]);

.config(function($stateProvider,$urlRouterProvider){
  $stateProvider
  .state('Login',{
    url:'/login',
    onEnter:["$state","$localStorage", '$rootScope' , '$ionicViewSwitcher',function($state,$localStorage, $rootScope, $ionicViewSwitcher){
        if((typeof($localStorage.userInfo)!== 'undefined') && (Object.keys($localStorage.userInfo).length !== 0)) {
                       $ionicViewSwitcher.nextTransition('none');
                       $state.go("Deployment");

        }
    }],
    templateUrl:'templates/login.html',
    controller:'LoginCtrl',
    resolve: {
            online: function(ConnectivityMonitor){
                return ConnectivityMonitor.isOnline();
        }
      }
  })

I don't know about the tutorial you're mentioning, however, you may want to check the post I wrote which goes literally step by step telling you where and why you should put some piece of code (may be useful if you're just starting with Ionic): http://www.nikola-breznjak.com/blog/codeproject/check-network-information-change-with-ionic-famework/ . 我不知道你提到的教程,但是,你可能想查看我写的帖子,它逐步告诉你应该放置一些代码的位置和原因(如果你是的话可能会有用)刚开始使用Ionic): http//www.nikola-breznjak.com/blog/codeproject/check-network-information-change-with-ionic-famework/

Also, I made the example code available freely on Github: https://github.com/Hitman666/IonicNetworkInfo . 另外,我在Github上免费提供了示例代码: https//github.com/Hitman666/IonicNetworkInfo You can download the project (if you don't want to go through the steps yourself) build it for your device and test it on the device. 您可以下载该项目(如果您不想自己完成这些步骤),请为您的设备构建它并在设备上进行测试。

Here are the steps from the blog posts: 以下是博文中的步骤:

Start a new Ionic project by doing: 通过执行以下操作启动新的Ionic项目:

ionic start IonicNetworkInfo blank

Then, change the directory to the newly created IonicNetworkInfo: 然后,将目录更改为新创建的IonicNetworkInfo:

cd IonicNetworkInfo

Install ngCordova with Bower: 使用Bower安装ngCordova:

bower install ngCordova

If by some chance you don't have bower installed, you can install it with npm: 如果您有可能没有安装bower,可以使用npm安装它:

npm install bower -g

Open up the www/index.html file in your favorite editor, and add the reference to ngCordova (just above the cordova.js script): 在您喜欢的编辑器中打开www / index.html文件,并添加对ngCordova的引用(就在cordova.js脚本上方):

<!-- This is what you should add, the cordova below you'll already have -->
<script src="lib/ngCordova/dist/ng-cordova.min.js"></script>

<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>

Install the ngCordova network plugin by executing the following command in your Terminal/Command prompt (you should do this from the root directory of your app; so, in our case the IonicNetworkInfo directory): 通过在终端/命令提示符中执行以下命令来安装ngCordova网络插件(您应该从应用程序的根目录执行此操作;因此,在我们的示例中为IonicNetworkInfo目录):

cordova plugin add org.apache.cordova.network-information

To check if you have successfully installed the plugin, you can run the following command (from the root directory – I won't be repeating this anymore; when I say you should run some command from the Terminal/Command prompt that, in this case, means from the root directory of the application): 要检查是否已成功安装插件,可以运行以下命令(从根目录 - 我将不再重复此操作;当我说你应该从终端/命令提示符运行一些命令时,在这种情况下,表示从应用程序的根目录):

cordova plugin list

You should see the following output: 您应该看到以下输出:

> cordova plugin list                                                                                                                           
com.ionic.keyboard 1.0.4 "Keyboard"
org.apache.cordova.network-information 0.2.15 "Network Information"

Open up the www/js/app.js file and add ngCordova to the dependencies list, so that basically the first line looks like this: 打开www / js / app.js文件并将ngCordova添加到依赖项列表中,这样第一行基本上如下所示:

angular.module('starter', ['ionic', 'ngCordova'])

Create a new controller in the www/js/app.js file called MyCtrl, with the following content: 在名为MyCtrl的www / js / app.js文件中创建一个新控制器,其中包含以下内容:

.controller('MyCtrl', function($scope, $cordovaNetwork, $rootScope) {
    document.addEventListener("deviceready", function () {

        $scope.network = $cordovaNetwork.getNetwork();
        $scope.isOnline = $cordovaNetwork.isOnline();
        $scope.$apply();

        // listen for Online event
        $rootScope.$on('$cordovaNetwork:online', function(event, networkState){
            $scope.isOnline = true;
            $scope.network = $cordovaNetwork.getNetwork();

            $scope.$apply();
        })

        // listen for Offline event
        $rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
            console.log("got offline");
            $scope.isOnline = false;
            $scope.network = $cordovaNetwork.getNetwork();

            $scope.$apply();
        })

  }, false);
})

In this controller you attach an event listener on the deviceready event (because it could be that the device would not have been yet initialized when this code runs) and you get the network information with: 在此控制器中,您可以在deviceready事件上附加事件侦听器(因为可能是此代码运行时设备尚未初始化)并且您获取网络信息:

$cordovaNetwork.getNetwork();

The information, about weather you're connected to the internet is obtained with the following line: 有关您连接到互联网的天气的信息可通过以下行获得:

$scope.isOnline = $cordovaNetwork.isOnline();

Then, you register two events $cordovaNetwork:online and $cordovaNetwork:online which trigger when the device gets online/offline. 然后,您注册两个事件$ cordovaNetwork:online和$ cordovaNetwork:online,当设备联机/离线时触发。 In them you then just update the $scope variables (). 在其中,您只需更新$ scope变量()。 Just for reference, the whole content of the www/js/app.js file should be: 仅供参考,www / js / app.js文件的全部内容应为:

// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic', 'ngCordova'])

.run(function($ionicPlatform, $cordovaNetwork, $rootScope) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }

  });
})

.controller('MyCtrl', function($scope, $cordovaNetwork, $rootScope) {
    document.addEventListener("deviceready", function () {

        $scope.network = $cordovaNetwork.getNetwork();
        $scope.isOnline = $cordovaNetwork.isOnline();
        $scope.$apply();

        // listen for Online event
        $rootScope.$on('$cordovaNetwork:online', function(event, networkState){
            $scope.isOnline = true;
            $scope.network = $cordovaNetwork.getNetwork();

            $scope.$apply();
        })

        // listen for Offline event
        $rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
            console.log("got offline");
            $scope.isOnline = false;
            $scope.network = $cordovaNetwork.getNetwork();

            $scope.$apply();
        })

  }, false);
});

In the index.html file, inside the ion-content tag paste the following content: 在index.html文件中,在ion-content标签内部粘贴以下内容:

<div class="card">
    <div class="item item-text-wrap">
        <h1>Network: {{network}}</h1>
    </div>
</div>


<div class="card">
    <div class="item item-text-wrap">
        <ion-toggle ng-model="isOnline" ng-checked="item.checked">
            <h1 ng-show="isOnline">I'm online</h1>
            <h1 ng-show="! isOnline">I'm offline</h1>
        </ion-toggle>
    </div>
</div>

Basically what we do here is we show the contents of the network variable (which is attached to the $scope via the controller). 基本上我们在这里做的是显示网络变量的内容(通过控制器附加到$ scope)。 Also, by using the ion-toggle component we show the “I'm online” / “I'm offline” notifications. 此外,通过使用离子切换组件,我们显示“我在线”/“我离线”通知。

Just for reference, the content of the whole index.html file should look like this: 仅供参考,整个index.html文件的内容应如下所示:

    <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <script src="lib/ngCordova/dist/ng-cordova.min.js"></script>
    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
</head>
<body ng-app="starter" ng-controller="MyCtrl">

    <ion-pane>
        <ion-header-bar class="bar-stable">
            <h1 class="title">Ionic Blank Starter</h1>
        </ion-header-bar>

        <ion-content padding="true">
            <div class="card">
                <div class="item item-text-wrap">
                    <h1>Network: {{network}}</h1>
                </div>
            </div>

            <div class="card">
                <div class="item item-text-wrap">
                    <ion-toggle ng-model="isOnline" ng-checked="item.checked">
                        <h1 ng-show="isOnline">I'm online</h1>
                        <h1 ng-show="! isOnline">I'm offline</h1>
                    </ion-toggle>
                </div>
            </div>

        </ion-content>
    </ion-pane>
</body>
</html>

In order to test this application you should run it on your device (because you can't disable network in iOS simulator). 为了测试此应用程序,您应该在您的设备上运行它(因为您无法在iOS模拟器中禁用网络)。 If you have an Android device plugged to your computer (and all the SDKs in place) you can run the following to commands to get your application running on your Android device: 如果您将Android设备插入计算机(以及所有适当的SDK),则可以运行以下命令以使您的应用在Android设备上运行:

ionic build android && ionic run android

Maybe you have not installed Network-Plugin. 也许你还没有安装Network-Plugin。 Please check this. 请检查一下。

Now, I think it would be a better approach to use 现在,我认为这将是一个更好的使用方法

$ionicPlatform.ready(function()  {
     $scope.network = $cordovaNetwork.getNetwork();
     $scope.isOnline = $cordovaNetwork.isOnline();

     $scope.$apply();
});

instead of document.addEventListener("deviceready", function () { 而不是document.addEventListener(“deviceready”,function(){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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