Search code examples
javascriptangularjsangularjs-service

AngularJS, why doesn't $http.get fire in my data service?


Code:

app.service('dataServices', function ($http) {
    ...
    this.getBases = function (lat, lng) {
        var promise = $http.get('/app/nearestbase/?lat=' + lat + '&lng=' + lng);
        promise.error(function (msg) { console.log(msg); });
        return promise;
    };
});

// root controller
function RootCtrl($scope, $location, dataServices) {
    navigator.geolocation.getCurrentPosition(function (p) {
        dataServices.getBases(p.coords.latitude, p.coords.longitude).success(function (data) {
            $scope.model.baseList = data;
        });
    });
};

As you can see in the root controller I get location, then use the location variables in the service I wrote dataServices.getBases. I've been able to test that the coordinates are successfully found, and dataServices.getBases is called, but the $http.get function doesn't fire. The server side method handling the call is never hit. There's no error, warnings... just nothing.

I have other functions in that service that use $http.get without problems.


Solution

  • Starting from angular 1.1.4 you need to call $http from the context of angular. Solution call $apply :

    // root controller
    function RootCtrl($scope, $location, dataServices) {
        navigator.geolocation.getCurrentPosition(function (p) {
            dataServices.getBases(p.coords.latitude, p.coords.longitude).success(function (data) {
                $scope.model.baseList = data;
            });
            $scope.$apply(); // ADD this line 
        });
    };