0

I have an Angular app, and in the controller I need to call a function which makes two http get requests, and I need this function to return these values just when they are resolved. I cannot make them in the $routeProvider resolve because this function needs a value obtained in the same controller.

I show part of the controller:

function myController(info) {
 var vm = this;
 vm.name = info.data.name;

 vm.extra_data = MyService.getExtras(name);
}

And here is part of the code of the service:

function myService($http, $q, API_EVENT1, API_EVENT2) {
 return {
  getExtras: getExtras
 }

 function getExtras(name) {
  var request1 = API_EVENT1 + '/' + name; 
  var request2 = API_EVENT2 + '/' + name;

 }
}

The function is not complete due to I have tried several methods, but I wasn't successful at all.

My problem is how to return (in getExtras function) both of the results of the requests. I have tried using $q.defer, $q.all and promises, but I'm not able to achieve it.

Using $q.all, for example, I got to retrieve the result, but when I call the function, the object extra_data is undefined, due to the requests have been executed asynchronously.

Thank you in advance for your responses.

2
  • Have you tried to store your $http responses to a global variable and use $q.all()as just a trigger for when all data is collected? Commented Aug 7, 2015 at 9:33
  • I got it! I have tried with that before, but I didn't return the defer correctly, but now I solved it returning the defer previously resolved when the $q.all is successful. Commented Aug 7, 2015 at 10:01

1 Answer 1

1

I would use $q.all to return combined promise from Service, and process result in controller. e.g.:

function myService($http, $q, API_EVENT1, API_EVENT2) {
  return {
    getExtras: getExtras
  }
  function getExtras(name) {
    return $q.all([
      $http({method: 'GET', url: API_EVENT1 + '/' + name}), 
      $http({method: 'GET', url: API_EVENT2 + '/' + name})])
     );
  }
}

function myController(info) {
  var vm = this;
  vm.name = info.data.name;

  MyService.getExtras(name).then(function(data) {
    vm.extra_data.first = data[0];
    vm.extra_data.second = data[1];
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that's what I did, more or less, but using $q.defer() in the serivce. Indeed, I thoguht I solved in this way, but the problem is that in the controller the vm.extra_data variable is not set in following lines, using .then function as you say. I mean, it is set in this function, with the correct value, but it is undefined in the following lines of the controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.