[英]AngularJS calling a function once I've made an array
背景
我正在制作一個angularJS應用程序
我有一個名為Map的對象。 Map有一個Transforms ID數組。
我需要在Maps的數組中獲取每個變換,然后將它們保存到Transforms數組而不是Transform ID數組。 到目前為止,除了在正確的時間調用函數之外,我已經完成了這項工作。
我想調用一個函數: doStuffWithTransformArray
使用完成的數組。
題
如何在數組完成填充后調用函數?
當前代碼(這有時僅適用)
$scope.makeTransformArray = function () {
$scope.transforms = [];
$scope.map.transforms.forEach(function(eachTransformID, index) {
Transform.get({uuid: eachTransformID.uuid}, function(transformResult) {
$scope.transforms[index] = transformResult;
if ($scope.transforms.length == $scope.map.transforms.length) {
$scope.doStuffWithTransformArray($scope.transforms);
return;
}
});
});
}
問題
僅當Map的數組中的最后一個Transform最后完成時,此當前代碼才有效。
如果數組填充時會調用doStuffWithTransformArray
兩次: (5) [y, y, y, empty, y]
第四個尚未填補,但第五個完成。
編輯1
這是我的轉換服務:
angular.module('serviceregistryApp')
.factory('Transform', function ($resource) {
var url = 'api/v1/transform/:uuid';
return $resource(url, {transform: '@transform', uuid: '@uuid'}, {
'save': {method: 'POST', headers: {"Authorization": "ABC"}},
'delete': {method: 'DELETE', headers: {"Authorization": "ABC"}},
'post': {method: 'POST', headers: {"Authorization": "ABC"}},
'get': {
method: 'GET', isArray: false,
headers: {
"Authorization": "ABC"
}, url: "api/v1/transform/:uuid",
transformResponse: function (data) {
return JSON.parse(data);
}
}
});
});
編輯2
正如評論中所建議的那樣,這似乎有效,但我發現它有點難看。
$scope.makeTransformArray = function () {
$scope.transforms = [];
var counter = 0;
$scope.map.transforms.forEach(function(eachTransformID, index) {
Transform.get({uuid: eachTransformID.uuid}, function(transformResult) {
$scope.transforms[index] = transformResult;
counter = counter + 1;
if (counter == $scope.map.transforms.length) {
$scope.doStuffWithTransformArray($scope.transforms);
return;
}
});
});
}
NgResource實例有一個名為$promise
的附加屬性,可用於在從服務器到達后轉換結果:
$scope.object = Transform.get({uuid: eachTransformID.uuid});
var promise = $scope.object.$promise;
var newPromise = promise
.then(function(object) {
var obj2 = transform(object);
$scope.object = angular.copy(obj2);
return obj2;
}).catch(function(errorResponse) {
console.log("ERROR", errorResponse.status);
throw errorResponse;
});
$scope.object.$promise = newPromise;
使用承諾進行后續鏈接或與$ q.all合並。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.