Manage connection rest api


#1

how can I handle a call to rest bees when they are not connected to the internet? I tried with this codice…ma does nothing

controller('AppCtrl',function($scope, $http,$sce,$timeout,$ionicLoading){

     document.addEventListener("online", function() {
       // Setup the loader
  $ionicLoading.show({
    content: 'Loading',
    animation: 'fade-in',
    showBackdrop: true,
    maxWidth: 200,
    showDelay: 0
  })
  
  //carico il link per la chiamata al REST
  var wordpressUrl ="http://www.mysites.it/sites/wordpress/wp-json/wp/v2/posts";
  $scope.$on('$ionicView.enter', function(){
    console.log('View1 Entered');
     $scope.doRefresh();
  });

  $scope.loadPost = function() {
  // effetuo la chimamata REST API
  $http.get(wordpressUrl)

    // risposta positiva
    .success(function(response,$timeout){
      console.log("Reveived getPosts via HTTP: ", response, status);     
    // Loading Json 
    $ionicLoading.hide();
    $scope.posts = response;
    console.log( response );
    })// fine success

    //risposta negativa
    .error(function(response, status){
      console.log("Error while received response. " + status + response);
    });// fine error

   }// End LoadPost


  // Refresh all'apertura della pagina 
  $scope.doRefresh = function() {
    
    console.log('Refreshing!');
    $timeout( function() {
      //simulate async response
      $scope.loadPost();
      //Stop the ion-refresher from spinning
      $scope.$broadcast('scroll.refreshComplete');
    }, 1000);

  };// Fine Refresh  
      }, false);// end event online 
})// Fine Controller

#2

You can use the network infomation Plugin to know if your device have internet connection or not.
By the boolean value: $cordovaNetwork.isOnline();
Or using this events:
$rootScope.$on('$cordovaNetwork:online', function() {});
$rootScope.$on('$cordovaNetwork:offline', function() {});


#3

i trial this code, but if

$scope.$on('$ionicView.enter', function(){
    console.log('View1 Entered');
    $scope.doRefresh();
});

but you are I try to put this event in cordova network, not load, I also tried to put:

$scope.$on('$ionicView.enter', function(){
   alert("connected")
});