Cannot read the property 'type' of undefin

2019-06-03 10:22发布

问题:

I am developing android application using cordova and ionic framework,using network plugin from here (https://github.com/apache/cordova-plugin-network-information). But the device ready alert fires off and then I get the the following error.

"TypeError: Cannot read property 'type' of undefined

Here is navigator object

navigator.connection.type 

I will get error in following line.

回答1:

use mine

document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
    checkConnection()
}

function checkConnection() {
    networkState = navigator.connection.type;
    var states = {};
    states[Connection.UNKNOWN] = 'Unknown connection';
    states[Connection.ETHERNET] = 'Ethernet connection';
    states[Connection.WIFI] = 'WiFi connection';
    states[Connection.CELL_2G] = 'Cell 2G connection';
    states[Connection.CELL_3G] = 'Cell 3G connection';
    states[Connection.CELL_4G] = 'Cell 4G connection';
    states[Connection.CELL] = 'Cell generic connection';
    states[Connection.NONE] = 'No network connection';
    alert('Connection type: ' + states[networkState]);
}


回答2:

For some reason, the navigator.connection object is not ready at the same time as cordova is.

You have to use a timeout, such as this one - designed for Angular/Ionic

   setTimeout(function(){
        var connection = connectionService.getConnection();
        console.log("connection : "+connection);
        $scope.connection = connection;
        $scope.$apply()
    }, 5000)