角度资源调用和$ q

run*_*ero 23 angularjs

伙计们,

我的代码设置如下:

$scope.init = function(){
  return $q.all([resource1.query(),resource2.query(),resource3.query()])
            .then(result){
               $scope.data1 = result[1];
               $scope.data2 = result1[2];
               $scope.data3 = result[3];


               console.log(data1); //prints as [$resolved: false, $then: function]

               doSomething($scope.data1,$scope.data2); 
                 }
}
Run Code Online (Sandbox Code Playgroud)

我的印象是只有在所有资源都得到解决后才会调用"then"函数.然而,这不是我在我的代码中看到的.如果我打印data1,我就会得不到解决.

关于我在这里失踪的任何线索?

小智 57

我遇到了这个问题,这让人非常困惑.问题似乎是调用资源操作实际上并不返回http promise,而是返回一个空引用(当数据从服务器返回时填充 - 请参阅$ resource docs的返回值部分).

我不确定为什么会导致.then(result)返回一个未解析的promises数组,但要获得每个资源的promise,你需要使用resource1.query().$promise.要重写你的例子:

$scope.init = function() {
  return $q.all([resource1.query().$promise, resource2.query().$promise, resource3.query().$promise])
           .then( function(result) {
             $scope.data1 = result[0];
             $scope.data2 = result[1];
             $scope.data3 = result[2];

             console.log($scope.data1);

             doSomething($scope.data1,$scope.data2); 
           })
}
Run Code Online (Sandbox Code Playgroud)

我希望能节省一些时间.

  • 这真的令人困惑,而且我可以告诉他们没有任何记录.在资源调用之后没有```$ promise```我在.then中得到了一个未实现的承诺,这没有任何意义.谢谢你. (3认同)