2013-12-12 3 views
1

자, 이제 Angular를 배웠으므로 쉽게 이동하십시오. 다음 코드 으로 작동하지만 더 나은 방법이 있어야합니다. 나는 내가 할 수있는 모든 것을 읽고있다. 그리고 내가 말할 수있는 것에서, 아마 이것들을 공장에서 설정하는 것이 최선일 수 있을까 ?? 지금까지, 내가 시도한 모든 것은 끝내 버리는 것들을 끝내지 만, 아마 나에게 잘못되어있는 것일지도 모른다.Angularjs - 여러 API 호출에 올바른 방법은 무엇입니까

전제 조건 내가 내가 3 API 호출의 총을 만드는 중이라서

  • , 두 가지가 있습니다 (그래서 내가이 추가로 지정 지침을 추가 할 수 있습니다) 모듈이 사용할 수 있도록해야

    • 사용하여 GET 방법 그러나 1 는 POST 방식을 사용하는

    내 코드 :

    $apiUrl = '_includes/gtmetrix.php'; // This is using a local proxy to access remote API. 
    $apiKey = ''; 
    $gapiUrl = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed'; 
    $gapiKey = '1z2x3c4v5b6n7m8a9s'; 
    $gapiStrategy = 'mobile'; 
    $requestUrl = '<?php echo $_POST['url']; ?>'; 
    
    function FetchCtrl($scope, $http, $templateCache) { 
    
        $scope.method = 'POST'; 
        $scope.url = $requestUrl; 
    
        $scope.fetch = function() { 
         $scope.code = null; 
         $scope.response = null; 
    
         $http({method: $scope.method, url: $apiUrl + '?url=' + $scope.url, cache: $templateCache}). 
         success(function(data, status) { 
          $scope.status = status; 
          $scope.data = data || "Request successful"; 
         }). 
         error(function(data, status) { 
          $scope.data = data || "Request failed"; 
          $scope.status = status; 
         }); 
        }; 
        $scope.fetch(); 
    
        $scope.fetchGoogle = function() { 
         $scope.code = null; 
         $scope.response = null; 
    
         $http({method: 'GET', url: $gapiUrl + '?url=' + $scope.url + '&key=' + $gapiKey, cache: $templateCache}). 
         success(function(data, status) { 
          $scope.status = status; 
          $scope.datag = data || "Request successful"; 
         }). 
         error(function(data, status) { 
          $scope.datag = data || "Request failed"; 
          $scope.status = status; 
         }); 
        }; 
        $scope.fetchGoogle(); 
    
        $scope.fetchGoogleMobile = function() { 
         $scope.code = null; 
         $scope.response = null; 
         // $scope.data = '<i class="fa fa-spinner fa-spin"></i>'; 
    
         $http({method: 'GET', url: $gapiUrl + '?url=' + $scope.url + '&key=' + $gapiKey + '&strategy=' + $gapiStrategy, cache: $templateCache}). 
         success(function(data, status) { 
          $scope.status = status; 
          $scope.datagm = data || "Request successful"; 
         }). 
         error(function(data, status) { 
          $scope.datagm = data || "Request failed"; 
          $scope.status = status; 
         }); 
        }; 
        $scope.fetchGoogleMobile(); 
    
        $scope.updateModel = function(method, url) { 
         $scope.method = method; 
         $scope.url = url; 
        }; 
    
    } 
    

    나는 지금 올바른 방식으로 도움을 주시면 대단히 감사하겠습니다. 고마워!

  • +0

    우선, $ q.all과 요청을 결합하여 콜백에 하나의 함수 만 사용할 수 있습니다. 또한 ngResource 모듈을 사용하여 API 호출을 추상화하는 옵션이 있습니다. –

    답변

    1

    편리한 방법은 편리한 $http.get()$http.post() 방법을 사용하는 것입니다. 또는 Klaster_1이 $resource을 사용하여 조사 할 것을 제안했기 때문입니다. 당신이 성취하고자하는 것이 무엇인지 모르지만 불필요한 코드가있는 것처럼 보입니다. 이런 식으로 시작해서 필요한만큼 추가 할 수 있습니다.

    function FetchCtrl($scope, $http) { 
        var googleApiBaseUrl = "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=<?php echo $_POST['url']; ?>&key=1z2x3c4v5b6n7m8a9s"; 
    
        $http.post("_includes/gtmetrix.php?url=<?php echo $_POST['url']; ?>") 
         .success(function(data) { 
          $scope.data = data; 
         }); 
    
        $http.get(googleApiBaseUrl) 
         .success(function(data) { 
          $scope.datag = data; 
         }); 
    
        $http.get(googleApiBaseUrl + "&strategy=mobile") 
         .success(function(data) { 
          $scope.datagm = data; 
         }); 
    } 
    
    1

    다음은 내가하는 일입니다. 나는 $http 대신에 $resource을 사용하고 있지만, 충분하면 충분합니다. $resource에는 내장 기능이 있기 때문에 사용할 수도 있습니다.

    내 공장 fn.

    .factory('WorkOrder', function($resource){ 
    
    // $resource Usage: $resource(url[, paramDefaults][, actions]); 
    return $resource('/controller/get/:id.json', {}, { 
        /* 
        * By default, the following actions are returned; modify or add as needed 
        * { 'get': {method:'GET'}, 
        * 'save': {method:'POST'}, 
        * 'query': {method:'GET', isArray:true}, 
        * 'delete': {method:'DELETE'} }; 
        */ 
    }); 
    
    }) 
    

    내 컨트롤러.

    // get the work order data using the work order id from the tag attribute 
    var getWO = function() { 
    
    WorkOrder.get({woId:$attrs.id}, 
    
        // success callback 
        function(response) { 
         // Assign the work order data to the scope 
         $scope.WorkOrder   = response.WorkOrder; 
        }, 
    
        // fail callback 
        function(response) { 
         // whatever... 
        } 
    ); 
    }; 
    getWO(); 
    

    성공과 실패에 대한 응답 방법을 알고 있기 때문에 내 성공 요인을 내 컨트롤러에 넣습니다. 또한 변수에 함수를 할당 한 다음 fn 호출을 $ timeout에 포함 시키거나 다른 곳에서 호출하려고 할 경우에 바로 호출합니다.

    원하는만큼 공장 fn을 만들 수 있습니다. 공장 fn 호출간에 종속성이있는 경우 컨트롤러의 성공 콜백 내에 종속 호출을 넣을 수 있습니다.

    희망 사항. 질문에 대한 답변입니다.

    관련 문제