我正在使用角度ui網格庫並嘗試填充自定義下拉過濾器。這個過濾器只能應用於特定的列,這就是爲什麼我寫了循環以便動態訪問列的原因。對於每個特定的列,我通過我的角度服務向api發送一個請求,以獲取過濾器的值,並且如果響應成功,我將每個列屬性ID與返回的數據ID進行比較,然後填充過濾器值。可變變量可從角度服務中的閉包訪問
這個問題似乎then
功能裏面,IDE顯示我警告
可變變量是從封閉
訪問和內部的then
功能沒有什麼作品。
我在這裏閱讀了多個主題,發現我必須執行自調用功能,但它不起作用。
那麼我的錯誤在哪裏?在此先感謝
代碼
for (var i = 0; i < $scope.columns.length; i++) {
// ===== rebuild columns tree =====
var execute_ids = [];
angular.forEach($scope.columns[i].property, function(){
if ($scope.columns[i].property.strict === true){
if(execute_ids.indexOf($scope.columns[i].property.propertyTypeId) === -1){
execute_ids.push($scope.columns[i].property.propertyTypeId);
lovServices.customPropFilterValue(execute_ids)
.then(function (response) {
(function() {
if (response.id == $scope.columns[i].property.propertyTypeId){
$scope.filter.push({
value: data.value,
label: data.value
});
$scope.columns[i].filter = {
type: uiGridConstants.filter.SELECT,
condition: uiGridConstants.filter.EXACT,
selectOptions: $scope.filter
};
}
})()
});
}
}
});
}
的代碼原有的部分
lovServices.customPropFilterValue(execute_ids)
.then(function (response) {
if (response.id == $scope.columns[i].property.propertyTypeId){
$scope.filter.push({
value: response.value,
label: response.value
});
$scope.columns[i].filter = {
type: uiGridConstants.filter.SELECT,
condition: uiGridConstants.filter.EXACT,
selectOptions: $scope.filter
};
}
});
編輯
我使用的解決方案通過提供@JuanTonina和警告走了,但似乎另一個問題。該i
內then
函數的返回錯誤值,因爲你有一個立即調用的函數表達式,或者IIFE簡稱
(function (i) { /* note that the lovServices call is INSIDE the IIFE*/
console.log($scope.columns[i].property.propertyTypeId)
// this console log returns correct ids (120, 123, 194)
lovServices.customPropFilterValue(execute_ids)
.then(function (response) {
console.log($scope.columns[i].property.propertyTypeId)
// this console log returns wrong ids (120, undefined, 114)
if (response.id == $scope.columns[i].property.propertyTypeId) {
$scope.filter.push({
value: data.value,
label: data.value
});
$scope.columns[i].filter = {
type: uiGridConstants.filter.SELECT,
condition: uiGridConstants.filter.EXACT,
selectOptions: $scope.filter
};
}
});
})(i)
您需要將'i'作爲IIFE參數傳遞給函數(函數(i){// code})(i )' –
@JuanTonina仍然沒有'lovServices.customPropFilterValue(execute_ids) 。然後(功能(響應){ (功能(I){// 我OCDE })(ⅰ); });' – antonyboom
對不起,只是指出你的IIFE只包含'.then'部分。你的代碼應該是這樣的: 'for(var i ...){(function(i){//循環的全部內容})(i)} 原因是您的變量'i'在使用回調函數之前發生了變化。作爲一個方面說明,如果你正在使用es6,做'for(let i = 0 ...)'也解決了這個問題 –