3

I try to make an application with PhoneGap and AngularJS that can be used online and offline (for Android device).
I want to get a list of people from the local database if the device is offline, and from a web service, using $http, if the device is online. But when the device is online, it doesn't work, web service isn't called.

I think the problem is PhoneGap asynchronous method. Indeed, in offline mode, it works but i need to use $scope.$apply to update my view. But that doesn't work for $http...

Does someone know how to use $http in asynchronous method?

function ListCtrl ($scope, $http){
    $scope.list = [];
    $scope.Id = 2;

    $scope.init = function(){
        document.addEventListener("deviceready", getList, false);
    }

    $scope.getAll = function(){ 

        $http({
            url: 'http://10.0.0.2:63414/myWebMethod/' + $scope.Id,
            method: 'GET',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
           }
        }).success(function(data) {
            $scope.list = data; 
        });
    }

    function getList(){
        var db = window.openDatabase("Database", "1.0", "list", 200000);
        var network = navigator.connection.type;
        if (network == "none"){
            // local database transaction works fine
        } else {
            $scope.getAll();
        }
        $scope.$apply();
    }

    $scope.init();
}
1
  • Had a similar problem today - $http.post wouldn't work properly in a separate thread (in my code it was in a FileReader event handler). I'm guessing $http has to be called from the main UI thread for some reason. Commented Apr 19, 2013 at 17:34

1 Answer 1

1

In the success callback you also have to trigger the digest with $scope.$apply();

$http({
        url: 'http://10.0.0.2:63414/myWebMethod/' + $scope.Id,
        method: 'GET',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
       }
    }).success(function(data) {
        $scope.list = data; 
        $scope.$apply();
    });

$http requests are asynchronous, so before you get any response from your request the program will keep executing and $scope.$apply() that you put after the if (network == "none") statement will run for nothing (you can remove it).

The PhoneGap query is working because you are using $scope.$apply() in it's callback, and you have to do the same in the $http success callback.

Sign up to request clarification or add additional context in comments.

1 Comment

Indeed, that was the problem. i don't know why i didn't try this. Thank you very much for your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.