0

Hello my code for service is:

angular.module('lucho1App').factory('ApiExample', ['$http', '$q', function($http, $q) {
    return {
        promiseToHaveData: function() {
            return $http.get('http://data.colorado.gov/resource/4ykn-tg5h.json').then(function(response) {
                var result = response.data;
                console.log(result);
                return result;
            }, function(response) {
                console.log('Error has ocurred');
            });
        }
    };
}]);

and my controller is:

angular.module('lucho1App')
  .controller('MainCtrl',['$scope', 'ApiExample',function MainCtrl($scope,ApiExample) {

    $scope.apiExampl=ApiExample.promiseToHaveData();
    console.log($scope.apiExampl);
}]);

the console.log in the service shows output which means that my request is successful but in the controller $scope.apiExampl is undefined where is my mistake?

2 Answers 2

1

A promise is asynchrnous, so it will be resolved later and the function in the then will be called at that very moment. The return in the callback permit to change the object passed to the next then call since promise are chainable object.

First you must return the promise object in your service :

return $http.get(...);

Second change your controller like this :

ApiExample.promiseToHaveData().then(function(data){
    $scope.apiExampl=data;
});

note that here i do =data because in your service you already extracted the data object from the response

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

1 Comment

Thanks a lot Walfrat!
0

You need to return promise

promiseToHaveData: function() {
    return $http.get('http://data.colorado.gov/resource/4ykn-tg5h.json');
}

And handle the success handler in controller

ApiExample.promiseToHaveData().success (function(response) {
    $scope.apiExampl = response.data;
    console.log($scope.apiExampl);
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.