sourcetip

HTTP 사용방법각도 설정JS가 맞습니까?구체적으로는 외부 API 호출에 대해서요?

fileupload 2023. 3. 19. 18:25
반응형

HTTP 사용방법각도 설정JS가 맞습니까?구체적으로는 외부 API 호출에 대해서요?

controller.js에는 다음과 같은 코드가 있습니다.

var myApp = angular.module('myApp',[]);

myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
    $http({
        method: 'GET',
        url: 'https://www.example.com/api/v1/page',
        params: 'limit=10, sort_by=created:desc',
        headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
     }).success(function(data){
         return data
    }).error(function(){
        alert("error");
    });
 }
});

myApp.controller('AngularJSCtrl', function($scope, dataService) {
  $scope.data = dataService.getData();
});

하지만 제가 CORS 관련 문제를 잘못 알고 있는 것 같습니다.이 전화를 걸 수 있는 올바른 방법을 가르쳐 주시겠습니까?감사합니다!

먼저, 당신의success()핸들러는 데이터를 반환할 뿐이지만 발신자에게는 반환되지 않습니다.getData()이미 콜백 중이기 때문입니다. $http를 반환하는 비동기 콜입니다.$promise따라서 데이터를 사용할 수 있는 경우에 콜백을 등록해야 합니다.

Promise와 Angular에 있는 $q 라이브러리를 찾는 것을 추천합니다.JS는 서비스 간에 비동기 호출을 전달하는 가장 좋은 방법이기 때문입니다.

알기 쉽게 하기 위해 호출 컨트롤러에 의해 제공되는 함수 콜백을 사용하여 다시 작성된 동일한 코드를 다음에 나타냅니다.

var myApp = angular.module('myApp',[]);

myApp.service('dataService', function($http) {
    delete $http.defaults.headers.common['X-Requested-With'];
    this.getData = function(callbackFunc) {
        $http({
            method: 'GET',
            url: 'https://www.example.com/api/v1/page',
            params: 'limit=10, sort_by=created:desc',
            headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
        }).success(function(data){
            // With the data succesfully returned, call our callback
            callbackFunc(data);
        }).error(function(){
            alert("error");
        });
     }
});

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData(function(dataResponse) {
        $scope.data = dataResponse;
    });
});

지금이다,$http는 실제로 $120을 반환하고 있기 때문에 다시 쓸 수 있습니다.

var myApp = angular.module('myApp',[]);

myApp.service('dataService', function($http) {
    delete $http.defaults.headers.common['X-Requested-With'];
    this.getData = function() {
        // $http() returns a $promise that we can add handlers with .then()
        return $http({
            method: 'GET',
            url: 'https://www.example.com/api/v1/page',
            params: 'limit=10, sort_by=created:desc',
            headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
         });
     }
});

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData().then(function(dataResponse) {
        $scope.data = dataResponse;
    });
});

마지막으로, 더 나은 방법으로,$http를 사용하여 헤더를 처리하는 서비스config()셋업하다$httpProvider예시는 $http 문서를 참조하십시오.

Promise를 사용하는 것이 좋습니다.

myApp.service('dataService', function($http,$q) {

  delete $http.defaults.headers.common['X-Requested-With'];
  this.getData = function() {
     deferred = $q.defer();
     $http({
         method: 'GET',
         url: 'https://www.example.com/api/v1/page',
         params: 'limit=10, sort_by=created:desc',
         headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
     }).success(function(data){
         // With the data succesfully returned, we can resolve promise and we can access it in controller
         deferred.resolve();
     }).error(function(){
          alert("error");
          //let the function caller know the error
          deferred.reject(error);
     });
     return deferred.promise;
  }
});

따라서 컨트롤러에서 다음 방법을 사용할 수 있습니다.

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData().then(function(response) {
        $scope.data = response;
    });
});

promise는 angularjs의 강력한 기능으로 콜백의 네스트를 회피하는 경우에 특히 편리합니다.

$http로 약속할 필요는 없습니다.반품은 2개뿐입니다.

 myApp.service('dataService', function($http) {
   this.getData = function() {
      return $http({
          method: 'GET',
          url: 'https://www.example.com/api/v1/page',
          params: 'limit=10, sort_by=created:desc',
          headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
      }).success(function(data){
        return data;
      }).error(function(){
         alert("error");
         return null ;
      });
   }
 });

인컨트롤러

 myApp.controller('AngularJSCtrl', function($scope, dataService) {
     $scope.data = null;
     dataService.getData().then(function(response) {
         $scope.data = response;
     });
 }); 

이거 드셔보세요

myApp.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
]);

useXDomain = true를 설정하는 것만으로는 충분하지 않습니다.또한 AJAX 요청은 AJAX임을 나타내는 X-Requested-With 헤더와 함께 전송됩니다.헤더의 삭제가 필요하기 때문에, 서버는 착신 요구를 거부하지 않습니다.

그러니까 약속이라는 걸 써야죠https://docs.angularjs.org/api/ng/service/$q에서 각도로 취급하는 방법을 읽어보십시오.기본적으로는 $http 지원 약속을 이행하기 때문에 고객님의 경우 이와 같은 조치를 취하겠습니다.

(function() {
  "use strict";
  var serviceCallJson = function($http) {

      this.getCustomers = function() {
        // http method anyways returns promise so you can catch it in calling function
        return $http({
            method : 'get',
            url : '../viewersData/userPwdPair.json'
          });
      }

  }

  var validateIn = function (serviceCallJson, $q) {

      this.called = function(username, password) {
          var deferred = $q.defer(); 
          serviceCallJson.getCustomers().then( 
            function( returnedData ) {
              console.log(returnedData); // you should get output here this is a success handler
              var i = 0;
              angular.forEach(returnedData, function(value, key){
                while (i < 10) {
                  if(value[i].username == username) {
                    if(value[i].password == password) {
                     alert("Logged In");
                    }
                  }
                  i = i + 1;
                }
              });
            }, 
            function() {

              // this is error handler
            } 
          );
          return deferred.promise;  
      }

  }

  angular.module('assignment1App')
    .service ('serviceCallJson', serviceCallJson)

  angular.module('assignment1App')
  .service ('validateIn', ['serviceCallJson', validateIn])

}())

Google Finance를 예로 들어 티커의 마지막 마감 가격과 업데이트된 날짜 및 시간을 가져옵니다.런타임 실행에 대해서는, YouTiming.com 를 참조해 주세요.

서비스:

MyApp.service('getData', 
  [
    '$http',
    function($http) {

      this.getQuote = function(ticker) {
        var _url = 'https://www.google.com/finance/info?q=' + ticker;
        return $http.get(_url); //Simply return the promise to the caller
      };
    }
  ]
);

컨트롤러:

MyApp.controller('StockREST', 
  [
    '$scope',
    'getData', //<-- the service above
    function($scope, getData) {
      var getQuote = function(symbol) {
        getData.getQuote(symbol)
        .success(function(response, status, headers, config) {
          var _data = response.substring(4, response.length);
          var _json = JSON.parse(_data);
          $scope.stockQuoteData = _json[0];
          // ticker: $scope.stockQuoteData.t
          // last price: $scope.stockQuoteData.l
          // last updated time: $scope.stockQuoteData.ltt, such as "7:59PM EDT"
          // last updated date & time: $scope.stockQuoteData.lt, such as "Sep 29, 7:59PM EDT"
        })
        .error(function(response, status, headers, config) {
          console.log('@@@ Error: in retrieving Google Finance stock quote, ticker = ' + symbol);
        });
      };

      getQuote($scope.ticker.tick.name); //Initialize
      $scope.getQuote = getQuote; //as defined above
    }
  ]
);

HTML:

<span>{{stockQuoteData.l}}, {{stockQuoteData.lt}}</span>

YouTiming.com 홈페이지 상단에 Chrome 및 Safari에서 CORS 정책을 비활성화하는 방법에 대한 메모를 배치했습니다.

서비스나 공장에서 정의된 약속을 호출할 때 공장에서 정의된 약속에서 응답을 받을 수 없으므로 반드시 서비스를 사용하십시오.서비스 내에서 정의된 약속이라고 합니다.

myApp.service('serverOperations', function($http) {
        this.get_data = function(user) {
          return $http.post('http://localhost/serverOperations.php?action=get_data', user);
        };
})


myApp.controller('loginCtrl', function($http, $q, serverOperations, user) {        
    serverOperations.get_data(user)
        .then( function(response) {
            console.log(response.data);
            }
        );
})

언급URL : https://stackoverflow.com/questions/20369377/how-to-use-http-get-in-angularjs-correctly-in-specific-for-an-external-api-cal

반응형