Search code examples
javascriptangularjsangularjs-scope

Custom Service returning undefined


Im creating a custom service, where it is working, is returning me in the function service the data, the problem is when i call it in the controller, it is returning me 'undefined'.

Service:

var toDoListServices = angular.module('toDoListServices', []);

    toDoListServices.factory('DataTasksService', function($http){
        return {
            getTasks: function(){
                $http.get('js/data.json').success(function(data){
                    return data;
                })

            }
        }
    });

Controllers:

var toDoListController = angular.module('toDoListController', []);

toDoListController.controller('ListController', ['$scope', 'DataTasksService', function($scope, DataTasksService){
        $scope.tasks = DataTasksService.getTasks();

}]);

App.js:

var myApp = angular.module('myApp', [
    'ngRoute',
    'toDoListController',
    'toDoListServices'
]);

Solution

  • getTasks doesn't return anything. A return inside success does nothing.

    You need to return the $http promise.

    Try

    toDoListServices.factory('DataTasksService', function($http){
        return {
            getTasks: function(){
                // return the promise
                return $http.get('js/data.json');               
    
            }
        }
    });
    

    In controller:

    DataTasksService.getTasks().then(function(response){
        $scope.tasks = response.data;
    });