如何在AngularJS中同步两个$ resource调用

时间:2014-06-06 23:26:40

标签: angularjs angular-resource angular-http

我正在尝试执行以下操作: 在我的控制器中,我有使用$ recource调用从数据库中获取数据的函数。服务' myService'

var fillSubData = function (containerToFill) {
  resService.getSubDataFromDB(//$resource service
    {params},
    function (res) {
      //do something with containerToFill with the result res add new values
    }
  );
}

var fillData = function (containerToFill) {
  resService.getDataFromDB(//$resource service
    {params},
    function (res) {
      //do something with containerToFill with the result res
      fillSubData(containerToFill);
    }
  );
}

控制器

$scope.dataToFill;// object

var initialize = function () {
  //by reference
  myService.fillData(dataToFill);
  // I need the dataToFill filled to do other thing with data recovered and built
  angular.forEach(dataToFill.someArrayBuilt, function (item) {
    //do something with item...
  })
}

我需要填充dataToFill才能恢复和构建数据,但资源调用是asyn,我该怎么做?

1 个答案:

答案 0 :(得分:0)

请注意,资源操作会返回包含$promise属性的对象。一旦异步调用返回,您可以使用它来继续回调:

myService.fillData(dataToFill).$promise.then(function() {
    // I need the dataToFill filled to do other thing with data recovered and built
    angular.forEach(dataToFill.someArrayBuilt, function (item) {
        //do something with item...
    })
});

要启用此功能,我建议您只需使用fillData方法返回资源调用的结果:

var fillData = function (containerToFill) {
    return resService.getDataFromDB(//$resource service ...