How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

后端 未结 7 1478
轻奢々
轻奢々 2020-11-29 16:58

I have the following code in the controller.js,

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

myApp.service(\'dataService\', function($http) {
delete $http.def         


        
7条回答
  •  感情败类
    2020-11-29 17:32

    Using Google Finance as an example to retrieve the ticker's last close price and the updated date & time. You may visit YouTiming.com for the run-time execution.

    The service:

    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
          };
        }
      ]
    );
    

    The controller:

    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
        }
      ]
    );
    

    The HTML:

    {{stockQuoteData.l}}, {{stockQuoteData.lt}}
    

    At the top of YouTiming.com home page, I have placed the notes for how to disable the CORS policy on Chrome and Safari.

提交回复
热议问题