0

아래 컨트롤러가 있습니다. 페이지로드시 아래에 표시된 $ http 서비스가 실행됩니다.

이제 다른 컨트롤러에서 컨트롤러의 $ http.post (...) 부분을 다시 호출하고 실행할 수 있습니다.


controller: function ($scope, $element, $http) { 

    function par() {    
     var xxx= null; 
     xxx = $scope.$parent.$root.ParentItems['xxx'].xxx; 
     var det = { xxx: xxx};    
     return det; 
    } 


$http.post('/api/values/entries/GoHere', par()).success(function (salData) { 

     var buildSHGraph = function (shData) { 
     //code code codes... 
     } 

     $scope.Array1 = []; 

     angular.forEach(salData, function (evt) { 
     //Code Code Codes 
     }); 

    buildSHGraph($scope.Array1); 

}); 

} 
+2

공장 또는 서비스를 이용할 수 있습니다. 서비스 또는 공장에 재사용 할 수있는 부분을 넣었을 때, 컨트롤러 중 하나에서 해당 서비스를 호출 할 수 있습니다. –

+2

$ http 메서드를 서비스로 옮기고 모든 컨트롤러에서 서비스를 전달하고 호출하십시오. – Neha

답변

5

은 당신이 서비스

angular.module("yourAppName", []). 
    factory("mySharedService", ['$http', function($http){ 
     return { 
      callPost: function(params) { 
       return $http.post('/api/values/entries/GoHere', params) 
        .success() 
        .error(); 
      } 
     }; 
}]); 

그런 다음 모든 컨트롤러에 주입하고 필요한 서비스 메소드를 호출 공유 만들 수 있습니다.

function FirstController($scope, mySharedService) { 
    $scope.params = {//..//}; 
    $scope.result1 = mySharedService.callPost(params) 
        .success(function(result){//..//}); 
} 

function SecondController($scope, mySharedService) { 
    $scope.params = {//..//}; 
    $scope.result2 = mySharedService.callPost(params) 
        .success(function(result){//..//}); 
} 
+0

감사합니다. 하지만이 부분은 "$ http.post ('/ api/values ​​/ entries/GoHere', par) 부분 만 이동할 수 있습니다." 공장에. 성공 부분은 여전히 ​​내 컨트롤러에 있습니다. 필자는 이와 같은 방법으로 그것을 시도했습니다. "mySharedService.callPost (par()). success (method());" 여전히 컨트롤러에 있지만 그 방법에 액세스 할 수 없습니다. 어떻게하는지 아십니까? – user1960948

+0

@ user1960948, 사례에 대한 답변을 업데이트했습니다. –

+0

안녕하세요 @Artyom 만약 내가 FirstController와 SecondController의 동일한 구현이 필요하다면? 내가 다른 컨트롤러에서 반복되는 것을 원하지 않는 이유는 다음과 같습니다. – user1960948

관련 문제