Skip to content
This repository has been archived by the owner on Sep 15, 2021. It is now read-only.

$cordovaNetwork: TypeError: Cannot read property 'type' of undefined #60

Closed
pellekrogholt opened this issue Jun 10, 2014 · 26 comments
Closed
Labels

Comments

@pellekrogholt
Copy link
Contributor

hi,

i'm using current master (7980897) of ng-cordova and like to use $cordovaNetwork in a login controller for example:

var loginControllers = angular.module('loginControllers', []);

loginControllers
  .controller('LoginCtrl', [
'$scope',
'$log',
'$state',
'$ionicLoading',
'$cordovaNetwork',
function($scope, $log, $state, $ionicLoading, $cordovaNetwork) {

  var type = $cordovaNetwork.getNetwork();
  var isOnline = $cordovaNetwork.isOnline();

  $log.log('network type', type);
  $log.log('network isOnline', isOnline);

  $ionicLoading.show({
    template: '... loading ...'
  });

}]);

when i deploy to an android (4.4) nexus 4 device i get a blank screen.

then with chrome://inspect device - i get the following in the console:

TypeError: Cannot read property 'type' of undefined
at Object.getNetwork (file:///android_asset/www/lib/ng-cordova/dist/ng-cordova.js:793:34)
at new <anonymous> (file:///android_asset/www/js/login/controllers.js:27:66)
at invoke (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:12641:17)
at Object.instantiate (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:12652:23)
at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:15711:28
at updateView (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:41075:30)
at file:///android_asset/www/lib/ionic/js/ionic.bundle.js:41031:9
at nodeLinkFn (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:15161:13)
at compositeLinkFn (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:14567:15)
at nodeLinkFn (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:15155:24) <ion-nav-view name="menuContent" animation="slide-left-right"> ionic.bundle.js:18366

"ng-cordova.js:793:34" ->

return navigator.connection.type;

but i can successfully in console do:

> navigator.connection.type
"wifi"

just for the record in the app.js where i load loginControllers i have ngCordova as a dependency:

  var myApp = angular.module('myApp', [
    'ionic',
    'ngCordova',
   ...

sorry if its not a error related to ng-cordova ....

//

pelle

@pbernasconi
Copy link
Contributor

@pellekrogholt I can't test on an Android, but have you tried putting the ng-cordova.js file before cordova.js like:

<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>

The docs don't say anything special about Android, so it may be an issue with installing the plugin.

Also check out http://stackoverflow.com/questions/15894201/checking-of-internet-connection-of-device-using-phonegap

@pellekrogholt
Copy link
Contributor Author

@pbernasconi thanks i tried to reverse the javascript files - it did unfortunately not solve the issue and still raises

TypeError: Cannot read property 'type' of undefined
at Object.getNetwork (file:///android_asset/www/lib/ng-cordova/dist/ng-cordova.js:793:34)

"so it may be an issue with installing the plugin." do you have other suggestions ?

can I say that the plugin is successfully installed when I can called it directly in the chrome console using chrome://inspect device or in the code for example a angular controller:

> navigator.connection.type
"wifi"

I don't understand why it works(tm) there and not inside the ngCordova.... any further hints/ suggestions warmly welcome...

@pbernasconi
Copy link
Contributor

Strange, I have it working on my iPhone using ngCordova. I'm thinking it's an issue with cordova or the plugin, and not ngCordova.

pellekrogholt added a commit to pellekrogholt/ionic_cordova_example_app that referenced this issue Jun 17, 2014
… Cordova service - both approaches raises 'type' of undefined for the navigator.connection.type because navigator.connection at some point when connection is not defined yet - even if 'deviceready' event have been fired - long story: ionic-team/ng-cordova#60
pellekrogholt added a commit to pellekrogholt/ng-cordova that referenced this issue Jun 18, 2014
… the ionic-team#60 - ensure demo app uses current ngCordova.js and set to newest ionic beta release
@pellekrogholt
Copy link
Contributor Author

@pbernasconi / others

ok it doesn't seem to be an issue with cordova (3.5.0) / cordova-plugin-network-information (tried: 0.2.9 / master version="0.2.10-dev)

controller example use case

i have done some more investigation on it and the odd thing is that when its called within a scope function call navigator.connection.type works(tm) but within init of controller it raises the mentioned type error - for example this controller:

  starterControllers
.controller('ConnectionCtrl', [
  '$scope',
  '$log',
  '$cordovaNetwork',
  function($scope, $log, $cordovaNetwork) {

    var connectionType = 'undefined';
    $scope.connectiontype = connectionType;

    try {
      $log.log($cordovaNetwork.getNetwork());
      $scope.connectiontype = $cordovaNetwork.getNetwork();
    } catch (e) {
      // probably:
      // ->
      // TypeError: Cannot read property 'type' of undefined
      // at Object.getNetwork (file:///android_asset/www/lib/ng-cordova/dist/ng-cordova.js:851:34)
      // ...          
      $log.log('$cordovaNetwork.getNetwork())', e);
    };

    $scope.connectionType = function () {        
      $scope.connectiontype = $cordovaNetwork.getNetwork();
    };

  }]);

full example here: https://github.com/pellekrogholt/ionic_cordova_example_app/tree/basic_ng_cordova

ngCordova $cordovaNetwork using promises

if have naively also tried an approach where I wrapped the network / navigator in a promise (inspirred by the ng-book https://www.ng-book.com):

https://github.com/pellekrogholt/ng-cordova/blob/navigator_connection_w_promises_ticket_60/src/plugins/network.js

motivation: for curiosity and a naive thought that it was a solution but i doubt that now ? because it seems like we at an early stage have the navigator but withouth the navigator.connection ...

more to come...

@welcoMattic
Copy link

Hi!

I just remember this : https://gist.github.com/welcoMattic/c6415563d6607fbedf3e

I wrote this piece of code during the beta-5 of Ionic, for a student project.

It may be already good ;)

@pbernasconi
Copy link
Contributor

@pellekrogholt did you resolve this issue? I think you may have to wrap the network call in a deviceready event like :

document.addEventListener("deviceready", function () {
  $cordovaPlugin.someFunction().then(success, error);
}, false);

// OR with Ionic

$ionicPlatform.ready(function() {
  $cordovaPlugin.someFunction().then(success, error);
});

@kristianbenoit
Copy link

I have a similar issue where I'm trying to hide the splashscreen and get the preferred language in module.run. This code always print both error and stacktrace even if the plugins are installed.

.run(function($ionicPlatform, $cordovaSplashscreen, $cordovaGlobalization) {

  $ionicPlatform.ready(function() {
    try {
      $cordovaSplashscreen.hide();
    } catch(e) {
      console.log(e.stack);
    }

    try {
      $cordovaGlobalization.getPreferredLanguage().then(function(lang) {
        $translate.preferedLanguage(lang);
      });
    } catch(e) {
      console.log(e.stack);
    }
  });
}])

I get the following output using logcat

D/CordovaLog( 5956): file:///android_asset/www/js/app.js: Line 31 : TypeError: Cannot call method 'hide' of undefined
D/CordovaLog( 5956):     at Object.hide (file:///android_asset/www/lib/ngCordova/dist/ng-cordova.js:3372:39)
D/CordovaLog( 5956):     at file:///android_asset/www/js/app.js:29:28
D/CordovaLog( 5956):     at Array.<anonymous> (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:37388:19)
D/CordovaLog( 5956):     at onPlatformReady (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2241:24)
D/CordovaLog( 5956):     at onWindowLoad (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2220:7)
D/CordovaLog( 5956): file:///android_asset/www/js/app.js: Line 39 : TypeError: Cannot call method 'getPreferredLanguage' of undefined
D/CordovaLog( 5956):     at Object.getPreferredLanguage (file:///android_asset/www/lib/ngCordova/dist/ng-cordova.js:1870:33)
D/CordovaLog( 5956):     at file:///android_asset/www/js/app.js:35:29
D/CordovaLog( 5956):     at Array.<anonymous> (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:37388:19)
D/CordovaLog( 5956):     at onPlatformReady (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2241:24)
D/CordovaLog( 5956):     at onWindowLoad (file:///android_asset/www/lib/ionic/js/ionic.bundle.js:2220:7)

I still get the same error if I wrap the calls in a $timeout of 1 sec.

@kristianbenoit
Copy link

My bad, I accidentally commented <script src='cordova.js'></script> with a bunch of other lines.

@pbernasconi
Copy link
Contributor

@kristianbenoit problem fixed? can I close this issue?

@kristianbenoit
Copy link

That is all good with me, @pellekrogholt issue resolved ?

@vitorventurin
Copy link

Hello @pellekrogholt

I'm using ionic and getting the same error with NativeAudio plugin:

Uncaught TypeError:
Cannot read property 'NativeAudio' of undefined ng-cordova.js:2531
preloadSimple ng-cordova.js:2531
(anonymous function) app.js:23
(anonymous function) ionic.bundle.js:37388
onPlatformReady ionic.bundle.js:2241
onWindowLoad ionic.bundle.js:2220

angular.module('ngCordova.plugins.nativeAudio', [])

.factory('$cordovaNativeAudio', ['$q', '$window', function ($q, $window) {

return {
  preloadSimple: function (id, assetPath) {
    var q = $q.defer();
    $window.plugins.NativeAudio.preloadSimple(id, assetPath, function (result) { // LINE WITH ERROR
      q.resolve(result);
    }, function (err) {
      q.reject(err);
    });

@kristianbenoit
Copy link

Make sure you call this inside a $ionicPlatform.ready(...). If you dont, cordova plugins might not be initialized => $window.plugins might be undefined yet.

@pbernasconi
Copy link
Contributor

Also check out the Common Issues in the docs, right after the install paragraph.

@pellekrogholt
Copy link
Contributor Author

@pbernasconi yes just close the issue - at the point of writing the issue - it was not clear to me that the call had to be wrapped with the $ionicPlatform.ready(...)

@MateenKadwaikar
Copy link

I am also facing the same issue. This is my controller

.controller('MapCtrl', ['$scope', '$rootScope', '$cordovaNetwork',

function($scope, $rootScope, $cordovaNetwork) {


    $ionicPlatform.ready(function() {

        var type = $cordovaNetwork.getNetwork()

        var isOnline = $cordovaNetwork.isOnline()

        var isOffline = $cordovaNetwork.isOffline()


        // listen for Online event
        $rootScope.$on('$cordovaNetwork:online', function(event, networkState) {
            console.log(event);
            console.log(networkState);
            var onlineState = networkState;
        })

        // listen for Offline event
        $rootScope.$on('$cordovaNetwork:offline', function(event, networkState) {
            console.log(event);
            console.log(networkState);
            alert(networkState);
        });
    });
}

]);

@diegognt
Copy link

( function ()
{
    'use strict';
    angular.module( 'ouNow.core' )
        .factory( 'ConnectionDetectiorService', ConnectionDetectiorService );

    ConnectionDetectiorService.$inject = ['$cordovaNetwork'];

    function ConnectionDetectiorService($cordovaNetwork)
    {
        var service = {
            thereIsCellConnection: thereIsCellConnection,
            thereIsWiFiConnection: thereIsWiFiConnection,
        };

        return service;

        function thereIsCellConnection() {
            console.log('to detect');

            console.log($cordovaNetwork.getNetwork());
        }

        function thereIsWiFiConnection() {
            // body...
        }

    }

I got:

TypeError: Cannot read property 'type' of undefined
at Object.getNetwork (http://localhost:8100/lib/ngCordova/dist/ng-cordova.js:5472:36)
at Object.t as thereIsCellConnection
at i (http://localhost:8100/dist/app.js:1:24049)
at new e (http://localhost:8100/dist/app.js:1:24360)
at invoke (http://localhost:8100/lib/ionic/js/ionic.bundle.js:13277:17)
at Object.instantiate (http://localhost:8100/lib/ionic/js/ionic.bundle.js:13285:27)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:17841:28
at chrome-extension://ighdmehidhipcmcojjgiloacoafjmpfk/dist/hint.js:1544:22
at IonicModule.controller.self.appendViewElement (http://localhost:8100/lib/ionic/js/ionic.bundle.js:52255:24)
at Object.IonicModule.factory.ionicViewSwitcher.create.switcher.render (http://localhost:8100/lib/ionic/js/ionic.bundle.js:50449:41)

I tried on nexus 6. Ionic 1.1.0

@vitorventurin
Copy link

Hey guys! I've got a solution! Start studying native iOS and Android! LOL #sadbuttrue

@alloyking
Copy link

@vitorventurin oh sure that's the solution. Not all my clients want to pay for both IOS and Android development. #sadbuttrue

@vitorventurin
Copy link

i agree with you @alloyking. i recommend ionic for simple projects but every app with low-level features are problematic. keep rockin'!!!
hugs
victor

@alloyking
Copy link

@vitorventurin I like hugs! Thanks for that. :)

@vitorventurin
Copy link

@alloyking i am from Brazil. everyone here loves hugs. haha. you are welcome. https://www.youtube.com/watch?v=izGwDsrQ1eQ

@chukwu
Copy link

chukwu commented Nov 26, 2015

guys...lets not get personal. I still cant find a fix for the original issue/error. $cordovaNetwork.isOnline()
type of undefined

@rigobcastro
Copy link

any solution?

@muthuspark
Copy link

This one worked for me, use window.navigator.network.connection.type

 document.addEventListener("deviceready", function() {
                var networkState = window.navigator.network.connection.type;
                if (networkState == Connection.NONE) {
                    $scope.nointernet = true;
                }
            }, false);


            document.addEventListener("offline", onOffline, false);

            function onOffline() {
                // Handle the offline event
            }

            document.addEventListener("online", onOnline, false);

            function onOnline() {
                // Handle the offline event
            }

@rigobcastro
Copy link

Ok, my error was because I had a code outside of the "$ionicPlatform.ready". Just is check all lines.

@gynekolog
Copy link

I had same problem. This plugin not work at browser, only on device. So instead:

document.addEventListener("deviceready", function () {
  $cordovaPlugin.someFunction().then(success, error);
}, false);

try

document.addEventListener("deviceready", function () {
 // work only on device
 if (window.cordova) {
   $cordovaPlugin.someFunction().then(success, error);
 }
}, false);

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests