添加回调到angularjs服务方法

时间:2015-10-23 17:06:17

标签: angularjs

有没有办法向调用服务的函数添加回调方法 在一个函数我调用多个服务方法,我想设置一个回调方法到该函数。 我试过这个但没有运气

$scope.MyFunction() = function()
{
    //Multiple Service calls
    $scope.callService1 = service.CallService1() //returns true on success
    $scope.callService2 = service.CallService2() //returns true on success
    $scope.callService3= service.CallService3() //returns true on success

    if($scope.callService1  && $scope.callService2 && $scope.callService3)
    {
        $scope.CallbackMethod ();
    }
}

$scope.CallbackMethod = function()
{
    alert('CallbackMethod')
}

我也尝试了这个,但它不同步,因为服务调用需要一些时间。

$scope.MyFunction() = function(CallbackMethod)
{
    //Refer Above Code
} 

CallService服务方法就像

一样简单
$http.post('/InstStrategy/ReadAll').then(function (response) {
    return true
});

1 个答案:

答案 0 :(得分:2)

假设CallService1CallService2CallService3是异步方法,它们应该返回延迟的承诺。例如:

this.CallService1 = function() {
  // Once the result is available resolve the promise.
  return $http.post('/InstStrategy/ReadAll').then(function(response) {
    return true;
  });
}

现在,是时候定义你的功能了:

$scope.MyFunction = function(callback) {
  var callService1 = service.CallService1(),
      callService2 = service.CallService2(),
      callService3 = service.CallService3();

  // We want to wait for all these three methods to complete.
  $q.all([callService1, callService2, callService3])
    .then(function(results)) {
          // Results is an array containing the results of each of your service calls.
          var allTrue = true;
          angular.forEach(results, function(result) {
            if (!result) allTrue = false;
          });

          // If all the service calls where true, perform our callback.
          if (allTrue) callback();
    });
};

请注意,allTrue检查不是必需的,因为promises系统地解析为true。