Usman Iqbal Usman Iqbal - 11 days ago 6
AngularJS Question

Angular Js - Why I am getting Undefiend in controller while I am getting data from service?

I have made a service and I am getting the data but it does not return any thing to controller.

My service. js file

app.factory('countryService', function ($http) {
return {
getCountries: function () {
$http.get('http://abc/countries')
.success(function (data) {
console.log(data);
})
.error(function (data) {
console.log(data);
});
}
};
});


and here is my controller

$scope.countries = function () {
$scope.countries_data = countryService.getCountries();
console.log($scope.countries_data);
};


What is my mistake ?

Answer

You might need to do some structural changes like following

app.factory('countryService', function ($http) {
    return {
        getCountries: function () {
            return $http.get('http://abc/countries'); //just return promise
        }
    };
});

Let service return the promise, Do other proceedings inside the controller,Define success callback and faiure callback for the same

$scope.countries = function () {
    $scope.countries_data = countryService.getCountries().then(success, failure); // callbaks
};

function success(response){
   console.log(response); // logs the results
}

function failure(response){
   console.log(response); // logs the errors if any
}

Hope this will help