0

I'm using an API in my app that has a few steps:

  1. Load full data from API 1
  2. Get some of that data and use that to make params for the next API call
  3. One that API call has been made, make a nvd3 chart (via a directive)

Controller:

$scope.deferred = $q.defer()

function makeChart(start, finish) {    
  api.getDetail(start, fin).then(function(throughput) {
    $scope.chartData = throughput;
    $scope.deferred.resolve();
  }, function(err) {
     console.log(err);
  })
}

api.getDetail(id).then(function(job){
  makeChart(job.start, job.finish);
})

// Directive

.directive('niceChart', [function(){
    return {
        restrict: 'E',
        replace: true,
        template: '<div>Nice Template!</div>',
        link: function (scope, element, attrs) {
        scope.deferred.then(function(){

         // Do stuff 

        })
      }
    }

 }])

When I do this I get scope.deferred.then is not a function.

What am I doing wrong here?

1 Answer 1

1

Use this code:

scope.deferred.promise.then(function(){
  // Do stuff 
})

The deferred object itself is not a promise, so it doesn't have the necessary methods. You should access the promise object: scope.deferred.promise.

But I recommend you to refactor the code to the following, sending the promise object as parameter:

var deferred = $q.defer()
$scope.promise = deferred.promise;

function makeChart(start, finish) {    
  api.getDetail(start, fin).then(function(throughput) {
    $scope.chartData = throughput;
    deferred.resolve();
  }, function(err) {
     console.log(err);
  })
}

api.getDetail(id).then(function(job){
  makeChart(job.start, job.finish);
})

////////////////////////////

.directive('niceChart', [function(){
    return {
        restrict: 'E',
        replace: true,
        template: '<div>Nice Template!</div>',
        link: function (scope, element, attrs) {
        scope.promise.then(function(){

         // Do stuff 

        })
      }
    }

 }])
Sign up to request clarification or add additional context in comments.

4 Comments

Oh? I'm a little confused. Looking at the first example here: docs.angularjs.org/api/ng/service/$q, does this mean that running $q.defer() adds a .then() property to whatever function it's inside?
$q.defer() returns a deferred object which has .resolve(), .reject() and .promise. The deferred.promise has .then(), .catch() and finally()
Ahhh ok, I didn't see the return deferred.promise in the link above and it messed me up. Thanks mate!
@Jascination Glad to help.

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.