6

I have build a simple service that makes multiple requests. The service has two methods. I cannot call one method from another inside the service.

Plunkr: http://plnkr.co/edit/2fERik4uTxbxlVOhncMd?p=preview

app.factory('Report', ['$http', function($http){
var Authors = {

    reports : [],
    requests :[{'url':'data/data.cfm','response':'first'},
               {'url':'data.json','response':'second'},
               {'url':'data.json','response':'third'},
               {'url':'data.json','response':'forth'}],


getReport : function(target, source, response, callback) {
    return $http({  url:source, 
                    method:"POST", 
                    params:{url : target}
                }).success(function(result) {
                    $scope.progress = response;
                    angular.extend($scope.user, result)
                    console.log($scope.user)
      }
      ).error(function(error){
                    $scope.progress = response
                })
},

    startQueue : function (target) {
        var promises = [];
        this.requests.forEach(function (obj, i) {
            console.log(obj.url)
            promises.push(getReport(target, obj.url, obj.response, function(value){
                reports.push(value);
                console.log(value)
            }));
        });
        $q.all(promises).then(function () {
            console.log("Finito");
        },function(error){
            console.log("errori")
        });
    }

};

return Authors;
}])

When I try to call getReport from inside startQueue I get error: getReport is not defined.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Tropicalista
  • 3,097
  • 12
  • 44
  • 72

2 Answers2

13

Change your factory to:

app.factory('Report', ['$http', function($http){
    var Authors = {

        reports : [],
        requests :[{'url':'data/data.cfm','response':'first'},
                   {'url':'data.json','response':'second'},
                   {'url':'data.json','response':'third'},
                   {'url':'data.json','response':'forth'}],
    };

    Authors.getReport = function(target, source, response, callback) {

    };
    Authors.startQueue = function (target) {

    };

    return Authors;
}])
AlwaysALearner
  • 43,759
  • 9
  • 96
  • 78
  • Thanks, this worked. But why I got error: Cannot call method 'all' of undefined, see the plunkr updated: http://plnkr.co/edit/2fERik4uTxbxlVOhncMd?p=preview – Tropicalista Sep 17 '13 at 15:38
  • I realise this is years later, but it would help to improve this answer by showing not only the good code, but to highlight what in the old code you changed, so people can quickly see what you fixed. – redfox05 Mar 04 '16 at 20:36
1

I know this is 'really late', but it looks like it's because you don't have $q injected.

Change:

app.factory('Report', ['$http', function($http){

to

app.factory('Report', ['$http','$q', function($http,$q){
bkbonner
  • 105
  • 2
  • 7