![](/img/trans.png)
[英]Syntax Error: Unexpected Identifier in for-loop in AngularJS $http.get
[英]Angularjs $http.get within loop
我在C#Web服務中使用angular.js,我需要逐項增加ng-repeat以在數據更新時向用戶顯示,為此我嘗試在循環內使用$ http.get進行刷新每個項目中的數據。 但是它不起作用
for (var i = 0; i < conditions.length; i++) {
var configFullAsset = {
params: {
Field: Field,
SAM_ConnectionString: SAM_ConnectionString,
TreeElemId: conditions[i][0],
ConditionDate: conditions[i][1]
}
};
$http.get('application.asmx/getExtFullAssetHealth', configFullAsset)
.success(function (responseExt) {
console.log("Element: ", i);
if (i == 0)
{
$scope.showData = responseExt;
$scope.fullAssetTable_loading = false;
$scope.fullAssetTable_loaded = true;
}
else
$scope.showData = $scope.showData.concat(responseExt);
//console.log("Data item: ", $scope.showData[i].Tag);
$scope.fullData = $scope.showData;
$scope.filterData(customFilter);
})
.catch(function (err) {
console.log("Error get object: ", err);
})
.finally(function () {
// Hide loading spinner whether our call succeeded or failed.
//$scope.loading = false;
$scope.fullData = $scope.showData;
$scope.filterData(customFilter);
$scope.fullAssetTable_loading = false;
$scope.fullAssetTable_loaded = true;
console.log($scope.fullData);
});
}
代碼的主要問題是休閑性:您在成功方法中將i用作索引,但並非您所期望的那樣,因為循環結束直到調用您的第一次成功為止。
您可以在第一階段建立這樣的請求,更容易閱讀:
function buildRequests() {
return conditions.map(function(condition) {
var configFullAsset = {
params: {
Field: Field,
SAM_ConnectionString: SAM_ConnectionString,
TreeElemId: condition[0],
ConditionDate: condition[1]
}
};
return $http.get('application.asmx/getExtFullAssetHealth', configFullAsset);
});
}
比您可以處理以下所有請求:
function handleRequests() {
var requests = buildRequests();
$q.all(requests)
.then(handleRequests)
.catch(function(error) {
console.log(error);
})
.finally(function() {
$scope.fullData = $scope.showData;
$scope.filterData(customFilter);
$scope.fullAssetTable_loading = false;
$scope.fullAssetTable_loaded = true;
});
}
比遍歷每個結果進行更改:
function handleResults(results) {
results.forEach(function(response, i) {
console.log("Element: ", i);
if (i == 0)
{
$scope.showData = response;
$scope.fullAssetTable_loading = false;
$scope.fullAssetTable_loaded = true;
}
else
$scope.showData = $scope.showData.concat(response);
//console.log("Data item: ", $scope.showData[i].Tag);
$scope.fullData = $scope.showData;
$scope.filterData(customFilter);
});
}
不要忘記注入$ q作為依賴項注入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.