Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs call an internal service function from self

Tags:

angularjs

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.

like image 351
Tropicalista Avatar asked Sep 17 '13 15:09

Tropicalista


2 Answers

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;
}])
like image 56
AlwaysALearner Avatar answered Sep 21 '22 23:09

AlwaysALearner


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){
like image 38
bkbonner Avatar answered Sep 21 '22 23:09

bkbonner