Angular:从服务中的控制器访问承诺

Angular: Accessing a promise from a controller within a service

我在我的应用程序中使用 API,它有几个步骤:

  1. 从 API 1
  2. 加载完整数据
  3. 获取一些数据并使用它为下一个 API 调用制作参数
  4. 一个 API 调用已经完成,制作一个 nvd3 图表(通过指令)

控制器:

$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('niceChart', [function(){
    return {
        restrict: 'E',
        replace: true,
        template: '<div>Nice Template!</div>',
        link: function (scope, element, attrs) {
        scope.deferred.then(function(){

         // Do stuff 

        })
      }
    }

 }])

当我这样做时,我得到 scope.deferred.then is not a function

我做错了什么?

使用此代码:

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

deferred对象本身不是一个promise,所以它没有必要的方法。您应该访问承诺对象:scope.deferred.promise.

但我建议您将代码重构为以下内容,将 promise 对象作为参数发送:

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 

        })
      }
    }

 }])