2015-10-23 17 views
0

有沒有任何添加回調方法的函數調用服務 函數我打電話給多個服務方法,我想爲該函數設置一個回調方法。 我試過,但沒有運氣將回調添加到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 
}); 
+0

聽起來像是在尋找承諾https://docs.angularjs.org/api/ng/service/$q – Hypaethral

+0

向我們展示CallService1功能的內容,請 – manzapanza

+0

用服務功能編輯問題。謝謝 – Gerry

回答

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檢查是不是真的有必要,因爲承諾被系統與真正的解決。

+1

謝謝Stefan :) – Gerry

+2

你可以更新你的第一個答案,而不使用「被遺忘的承諾」模式嗎?你的回答會因此爲許多人是在他們的最佳利益閱讀的最佳實踐進行讀取。 – Icycool

+1

我編輯了您的答案,以便在$ http調用失敗的情況下返回拒絕的承諾。正如lycool所指出的,您的原始答案使用了反模式。閱讀http://blog.ninja-squad.com/2015/05/28/angularjs-promises/ –

相關問題