JVG
JVG

Reputation: 21150

Angular: Accessing a promise from a controller within a service

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?

Upvotes: 0

Views: 121

Answers (1)

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19080

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 

        })
      }
    }

 }])

Upvotes: 1

Related Questions