2017-10-10 35 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