JK_Jha JK_Jha - 16 days ago 6
AngularJS Question

returning promise from factory method after combining multiple API calls and processing

I have been using the promise returned by simple http method from a long while. But I have a need where I need to first chain multiple API call and process the data and return that data. Problem what I am facing with current implementation is the factory is not returning the promise and hence not waiting for data and executes next line of the controller.

app.factory('mytestService', ['$http', function($http){
getSomeDataById: function(id){
var userAllProjects = [];
var myHelperService = this.getSecondData;
this.getFirstData(id).then(function(response){ // first api call
var idObjectValue = response['result'][0]['id'];
myHelperService(idObjectValue).then(function(response){ //second api call
userAllProjects= response['projectList']
});
});
return userAllProjects
}
]);


Now in controller when I do:

$scope.allProjects = mytestService.getSomeDataById(1234);
console.log($scope.allProjects);


the console prints undefined. I know this is because, it doesn't wait for the service to complete and exscutes the next line.

I am little novice to angular promises, so no idea how to handle that. Can anyone please help me here.
Please let me know if you need any further information.

Answer

Try following code.

getSomeDataById: function(id){
  var userAllProjects = $q.defer();
  var myHelperService = this.getSecondData;
  this.getFirstData(id).then(function(response){ // first api call
     var idObjectValue = response['result'][0]['id'];
     myHelperService(idObjectValue).then(function(response){ //second api call
       userAllProjects.resolve(response['projectList'])
    });
  });
  return userAllProjects.promise;
}

The idea is, you create a deferred object first, and return the promise. When data is available you resolve the deferred object and the data will be made available in your controller.

Note: you will need to add dependency on $q

Ref: https://docs.angularjs.org/api/ng/service/$q

Comments