如何在 AngularJS 中将参数传递给 promise

How to pass arguments to promise in AngularJS

我开发了一个带有指令的小型 angular 应用程序。 为了从服务器端检索数据,我使用 ngRoute。检索数据后,我将结果绑定到范围 属性 并使用 ng-repeat 解析结果,如下所示:

 <div class="col-xs-12" ng-repeat="clsRow in classificatorData">
   <span>{{clsRow.code}}</span>
 </div>

此函数从资源中检索数据

var getClassificatorDataScope = function (criteria, predicate) {
                references.initialize('classificators');
                references
                    .getRefereces(null, $scope.classificatorType, criteria, predicate == null ? "NONE" : predicate, $scope.limitLevel, null)
                    .$promise.then(function (result) {
                        $scope.classificatorData = result.Data;
                    });


            };

一切正常。但是如果我尝试像这样实现传递结果数据容器(dataScope)

var getClassificatorDataScope = function (criteria, predicate, dataScope) {
                references.initialize('classificators');
                references
                    .getRefereces(null, $scope.classificatorType, criteria, predicate == null ? "NONE" : predicate, $scope.limitLevel, null)
                    .$promise.then(function (result) {
                        dataScope = result.Data;
                    });


            };

然后像这样在控制器中使用它

getClassificatorDataScope("CODE", null, $scope.classificatorData);

我没有任何数据。请帮助我理解这种行为。

问题可能出在您的 references.getRefereces 方法中。它应该 return 一个承诺,然后用正确的结果解决它(我看到你试图从结果访问 "Data" 属性。)。像这样:

reference.getReferences = function() {
       var deferred = $q.defer();  
       someAsyncOperations(function callback(){
          deferred.resolve({Data: result})  // make sure you have the "Data" attr
       })
       return deferred.promise;

// or if someAyncOperations already return a promise
// return someAsyncOperations.then(function(result) {
//    return {Data: result};
// });
    }

似乎在第二个示例中,您试图将从服务器检索到的数据分配给 dataScope,但由于 AJAX 数据加载是异步的,因此 $promise 的解析时间晚于您的模板ng-repeat 已绘制。

所提供的代码不足,无法编写整个示例 - 应如何实施。但基本上你应该 return $promise 从你的服务和控制器中更改 $scope 变量

promise.then(function() {
//do stuff with $scope variables
})

这里有 2 个问题。

dataScope = result.Data;

第一个是这个。这并不像您期望的那样。 它不会取代 $scope.classificatorData。它所做的只是将 getClassificatorDataScope 中的局部 dataScope 变量替换为 result.Data(是的,它不是 "passed by reference")。

其次,您错误地使用了承诺。您 return promise 用于监听,而不是将范围传递给谁知道在哪里。您的数据层一般不应知道 $scope 或 UI。 Return 对控制器的承诺,并让它监听来自它的数据。

// In your function
var getClassificatorDataScope = function(criteria, predicate) {
  references.initialize('classificators');
  return references
    .getRefereces(null, $scope.classificatorType, criteria, predicate == null ? "NONE" : predicate, $scope.limitLevel, null)
    .$promise
};

// In your controller
getClassificatorDataScope("CODE", null).then(function(result){
  $scope.classificatorData = result.Data;
});