Cordova network plugin does not work on a controller

1

I am using a plugin in order to get the status and connection type of my mobile device through an application. But the plugin only works within $ionicPlatform.ready , at least that happened to me, when I execute it within controller the result of the connection type is unknow .

This is the plugin: Netwrok Plugin ngCordova

Code

angular.module('starter', ['ionic', 'ngCordova'])
    .run(startApp)
    .controller('networkCtrl', networkCtrl);

startApp.$inject = ['$ionicPlatform', '$cordovaNetwork'];

function startApp($ionicPlatform, $cordovaNetwork) {

    $ionicPlatform.ready(function() {

        if (window.cordova && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            cordova.plugins.Keyboard.disableScroll(true);
        }

        if (window.StatusBar) {
            StatusBar.styleDefault();
        }

        var netInfo;
        netInfo = $cordovaNetwork.getNetwork();
        console.log(netInfo);

    });

}

networkCtrl.$inject = ['$scope', '$cordovaNetwork'];

function networkCtrl($scope, $cordovaNetwork) {

    var netInfo;
    netInfo = $cordovaNetwork.getNetwork();
    console.log(netInfo);

}
    
asked by Pedro Miguel Pimienta Morales 22.10.2016 в 20:17
source

1 answer

2

Taken from the documentation : (my translation)

  

... This means that the web app can potentially invoke Cordova Javascript code before its native counterpart is fully loaded.   The deviceready event triggers when Cordova is fully loaded ...

What I mean is that the controller can be started before Cordova is fully loaded. The technique is to put the code that reads the state of the network within the event deviceready . Do not worry if the event is loaded too late (ie after the event is launched) because Cordova invoked the callback immediately if the event was already launched before.

function networkCtrl($scope, $cordovaNetwork) {

  // $ionicPlatform.ready(function() { <- falta injectar
  document.addEventListener("deviceready", function () {
    console.log(
      $cordovaNetwork.getNetwork()
    ) 
  });

}
    
answered by 23.10.2016 / 03:21
source