2017-10-10 75 views
0

我有不同的複選框,它們也有單獨的端點。我想根據複選框選擇相應的端點,並將所有結果返回到一個數組中以進一步過濾。到目前爲止,我在網上找到的資源要求我使用$ q.all鏈接所有請求,但似乎無法根據所選的複選框來實現此目的。根據選中的複選框返回結果數組

這是我到目前爲止。我需要幫助,請。

模板

<div class="col-sm-4" ng-repeat="item in checkBoxes"> 
    <input type="checkbox" ng-model="item.selected"> 
    <span>{{item.name}}</span>  
</div> 
<button ng-click="getResult()">Get Result</button> 

控制器

$scope.checkBoxes = [ 
    { 
    id: 1, 
    name: "option1", 
    selected: false 
    }, 
    { 
    id: 2, 
    name: "option2", 
    selected: false 
    }, 
    { 
    id: 3, 
    name: "option3", 
    selected: false 
    } 
]; 

// Checking which option is checked 

$scope.optionChecked = function(choice) { 
    $scope.details = []; 
    angular.forEach(choice, function(value, key) { 
    if (choice[key].selected) { 
     $scope.details.push(choice[key].name); 
    } 
    }); 
}; 

function isInArray(name,details) { 
    for (var i = 0; i < details.length; i++) { 
     if (details[i].toLowerCase() === name.toLowerCase()){ 
     return true; 
     } 
    } 
    return false; 
} 

function loadPage() { 
    if (isInArray("option1",$scope.details)){ 
     Servicename.endpoint1() 
     .success(function(response) { 
     console.log(response); 
     }); 
     }) 
     .error(function() { 
     console.error(arguments); 
     $scope.failed = true; 
     }) 
    } 
if (isInArray("option2",$scope.details)){ 
     Servicename.endpoint2() 
     .success(function(response) { 
     console.log(response); 
     }); 
     }) 
     .error(function() { 
     console.error(arguments); 
     $scope.failed = true; 
     }) 
    } 
} 

這是我想達到的效果。 finalResult從loadPage函數中獲取。

$scope.getResult = function() { 
    $scope.optionChecked($scope.checkBoxes); 
    if($scope.details.length > 0 && $scope.details[0] !== null){ 
    loadPage().then(function(finalResult) { 
     console.log("This should return the final array based on checked 
     boxes") 
    }); 
} 

回答

0

$q.all保留與原生Promise.all相同的API。它需要一系列的承諾,並返回一個新的承諾,當所有的子承諾解決時,承諾就會解決。

您應該從每個Service.endpointX()呼叫中獲取回覆承諾並將其存儲在數組x中。記住

function loadPage() { 
    var promises = []; 

    if (isInArray("option1",$scope.details)){ 
    promises.push(Servicename.endpoint1().success(...).error(...)) 
    } 

    if (isInArray("option2",$scope.details)) { 
    promises.push(Servicename.endpoint2().success(...).error(...)) 
    } 

    return $q.all(promises) 
} 

記住,對孩子的承諾附加一個成功處理程序,將導致孩子承諾在一個錯誤的情況下解決,而不是拒絕,:然後返回Promise.all(x)。這意味着如果您所做的任何HTTP調用都被拒絕,則使用$q.all()創建的父承諾仍將解決。爲了避免解決錯誤處理程序中的承諾,請返回$q.reject(someOptionalValue)

ServiceName.endpoint1().success(...).error(e => { alert(e); return $q.reject(); }); 
+0

它工作。非常感謝@nicooga,我很感激。 – Hopez