LachezarB
LachezarB

Reputation: 51

Service injection in controller AngularJs

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?

Upvotes: 0

Views: 49

Answers (2)

Satpal
Satpal

Reputation: 133403

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);
});

Upvotes: 0

Walfrat
Walfrat

Reputation: 5353

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

Upvotes: 1

Related Questions