2015-01-04 2 views
0

angularjs의 forEach 루프에 $ http.post 요청을하는 데 문제가 있습니다. 마지막 루프 (obj.dtype == 'Install')에서만 $ http.post가 실행됩니다. 어떻게 모든 루프에서 $ http.post 작업을 할 수 있습니까?

angular.forEach($scope.data, function(obj, i){ 
    if(obj.dtype == 'Remove'){ 
    $http.post('url1').success(); 
    } else if(obj.dtype == 'Install'){ 
    $http.post('url2').success(); 
    } 
}); 

미리 감사드립니다.

해결책 :

angular.forEach($scope.data, function(obj, i){ 
    if(obj.dtype == 'Remove'){ 
    url = 'url1'; 
    dataToUpload = {}; 
    } else if(obj.dtype == 'Install'){ 
    url = 'url2' 
    dataToUpload = {}; 
    } 

$http.post(url, dataToUpload).success(); 
}); 

답변

0

나는 AngularJS와 $http POST 호출로 아무 잘못 볼 수 없습니다. 다음 코드는 POST가 4 번 실행되는 곳에서 작동합니다.

app.controller('MainCtrl', ['$scope','$http', function($scope, $http) { 
    $scope.name = 'World'; 
    $scope.data = ["Data1","Data2","Data3","Data4"] 

    angular.forEach($scope.data, function(obj, i){ 
    $http({method:'POST', url: 'http://httpbin.org/post', data: obj}). 
     success(function(data, status) { 
      $scope.status = status; 
      $scope.data = data; 
     }). 
     error(function(data, status) { 
      $scope.data = data || "Request failed"; 
      $scope.status = status; 
     }); 
    }); 
}]); 

나는 $scope.data의 내용과 $http의 구문을 검토 건의 할 것입니다.

+0

foreach 루프 내의 if 문이 요인 일 수 있습니까? 데이터의 값 유형에 따라 게시물에 2 $ http 요청이 있습니다. – MarkJ

+0

if 문장에 console.log를 두어 읽었는지 무시할 것인지 결정하려고했습니다. 나는 콘솔에서 응답을 얻었고 $ http.post가 마지막 데이터가 될 때까지 어떻게 든 해고되지는 않았습니다. – MarkJ

+0

'.post' 메쏘드 대신에'$ http ({})'문법을 사용해보십시오. 위에 주어진 코드를 컨트롤러에 추가하여 실행할 수 있습니까? 또한 가능한 경우 정확한 코드를 제공하십시오. –

관련 문제