1

I have an Angular.js application and I need to call three different resources and once they all complete, use them together. My three calls are below.

# Get the curriculum
$scope.curriculum = CurriculumResource.get id: $routeParams.id

# Get the list of courses
$scope.courses = CourseResource.query()

# Get the list of groups
$scope.groups = GroupResource.query()

How can I perform more logic once I know the requests are all completed. I've tried using $watchGroup shown below and $watchCollection but neither seem to be working.

$scope.$watchGroup ['curriculum', 'courses', 'groups'], ->
    # Shouldn't this run each time something in the above array changes?
    console.log 'Only runs once'

    # The values of the items in the below if statement eventually give a true result
    # but the if statement never runs when they are true
    if $scope.curriculum.groups and $scope.groups.length          
      console.log 'never gets here!'

2 Answers 2

2

I believe you could accomplish this with $q.all assuming all of your requests return promises. Something like

$q.all([CurriculumResource.get({id: $routeParams.id}), CourseResource.query(), GroupResource.query()])
  .then(function(results){
     // results will be an array of values from resolved promises in the original order
   })
   .catch(function(err) {
     // will fail on any rejected promise
   });
Sign up to request clarification or add additional context in comments.

1 Comment

I am using this and the Courses and Groups return fine but the Curriculum results (results[0]) is still an unresolved response. I am not sure why. The form on the page that this controller is on displays the curriculum data fine so the promise does get resolved. I am just using the $resource module with default settings. The only thing really set in my CurriculumResource is the url.
1

Inject $q service, and use it this way:

$q.all(
  [
  CourseResource.query(),
  CurriculumResource.query(),
  GroupResource.query()
  ]
).then(function(response) {
  $scope.courses = response[0];
  $scope.curriculum = response[1];
  $scope.groups = response[2];
  // do what you need to do when all data is available
});

Also, you need to make sure your services are returning $q deferreds, all request returned by $http are deferred so you can return them, but maybe you want to wrap it to process the results (for example to extract the important info, o to preprocess data with model logic):

...
query: function() {
  return $http.get("...url...").then(function(response) {
    //process response here before return it
  }); // of course, the use of .then is optional
}
...

Comments

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.