JohnP
JohnP

Reputation: 1076

How to get used http call parameter in AngularJs promise?

I would like to log if there is no data in some returned Javascript object. Since http calls are asynchronous, my implementation doesn't work. I'm checking if the object is empty and if it is, I would like to log it's id. How could I get the right scenarioId to my else statement?

for (var i in $scope.scenarioData){
                var scenarioId = $scope.scenarioData[i].id;                
                dataService.getResultsByScenarioId(scenarioId).then(function(response){
                    if (Object.keys(response.data).length != 0){                    
                        //This is not interesting in this context
                    }
                    else{
                        //I would like to log the called scenarioId here
                        $log.info("No data in scenarioId: " + scenarioId);
                    }
                });
        }

This is the used service

ptraApp.service('dataService', function($http) {
    this.getResultsByScenarioId = function(id) {
        return $http({
            method: 'GET',
            url: '/ptra/resultArchive/' + id,
        });
    }
});

Upvotes: 0

Views: 54

Answers (2)

user3227295
user3227295

Reputation: 2156

Extract the function that call to servive to external function for example:

for (var i in $scope.scenarioData){
      var scenarioId = $scope.scenarioData[i].id;
      getResult(scenarioId)
}

function getResult(scenarioId){
    dataService.getResultsByScenarioId(scenarioId).then(function(response){
                if (Object.keys(response.data).length != 0){                    
                    //This is not interesting in this context
                }
                else{
                    //I would like to log the called scenarioId here
                    $log.info("No data in scenarioId: " + scenarioId);
                }
            });
}

Upvotes: 2

Hussein Zawawi
Hussein Zawawi

Reputation: 2937

Should be something like that snippet:

ptraApp.service('dataService', function($http) {
        this.getResultsByScenarioId = function(id) {

    return $http({ method: 'GET', url: '/ptra/resultArchive/' + id}).
      success(function (data, status, headers, config) {
        console.log(data);
      }).
      error(function (data, status, headers, config) {
        // ...
   );
}});

Upvotes: 0

Related Questions