将ajax请求转换为angular $ http

时间:2016-09-06 00:53:07

标签: angularjs angular-http

我正在学习如何使用角度,而我对api的请求并不是那么熟悉。我正在尝试使用http://api.football-data.org/index练习。我想从角度工厂得到的json数据是http://api.football-data.org/v1/competitions/426/leagueTable。现在我在控制台中收到错误

  

'angular.js:13920 TypeError:无法读取未定义的新属性'getLeagueData'...'

我的CLI显示我正在加载我的所有脚本文件,并且在尝试引入工厂并创建getLeagueData函数之前测试了我的控制器并且它正在运行所以我知道我的问题是在创建基本控制器之后。我认为这可能与我需要我收到的身份验证令牌的标题有关,但我不确定我是否没有正确添加它。这是我的代码

HTML

<!DOCTYPE html>
<html lang="en" ng-app='bplApp'>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title><%= title %></title>

<!-- Bootstrap -->
<link href="/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<!--Font Awesome-->
<link rel="stylesheet" href="/bower_components/font-awesome/css/font-awesome.min.css">
<!--Custom-->
<link rel='stylesheet' type='text/css' href='/stylesheets/main.css'>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class='leagueCheck' ng-controller='tableController as table'>
  <div class='container'>
    <div class='row'>
      <div class='col-xs-12'>
        {{table.test}}
      </div>
    </div>
  </div>
</div>



<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="/bower_components/jquery/dist/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src='/bower_components/angular/angular.min.js'></script>
<!--Module-->
<script src='bplApp.js'></script>
<!--Controller-->
<script src='/controllers/tableController.js'></script>
<!--Service-->
<script src='/services/footballData.js'></script>

模块

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

控制器

app.controller('tableController', ['$scope', 'footballData', function($scope, footballData){
var self = this;

self.test = 'is working';
self.leagueStats = [];

footballData.getLeagueData().then(function(data){
    self.leagueStats = data;
    console.log(self.leagueStats);
  })
}])

app.factory('footballData', [function($http){
      return {
        getLeagueData: function(){
            return $http({
              method: 'GET',
              url: 'http://api.football-data.org/v1/competitions/426/leagueTable',
              headers:{
                  'X-Auth-Token': '3e629af30fce46edaa6ead20e007a276'
              }
            })
        }  
      }
}])

api显示使用它的原始ajax代码示例如下所示

$.ajax({
  headers: { 'X-Auth-Token': 'YOUR_API_TOKEN' },
  url: 'http://api.football-data.org/v1/fixtures?timeFrame=n1',
  dataType: 'json',
  type: 'GET',
}).done(function(response) {
  // do something with the response, e.g. isolate the id of a linked     resource        
  var regex = /.*?(\d+)$/; // the ? makes the first part non-greedy
  var res = regex.exec(response.fixtures[0]._links.awayTeam.href);
  var teamId = res[1];
  console.log(teamId);
}); 

1 个答案:

答案 0 :(得分:2)

您在工厂使用了数组表示法。要么直接使用它,要么在数组中声明$ http:

app.factory('footballData', ["$http", function($http){
      return {
        getLeagueData: function(){
            return $http({
              method: 'GET',
              url: 'http://api.football-data.org/v1/competitions/426/leagueTable',
              headers:{
                  'X-Auth-Token': '3e629af30fce46edaa6ead20e007a276'
              }
            })
        }  
      }
}])

OR

app.factory('footballData', function($http){
      return {
        getLeagueData: function(){
            return $http({
              method: 'GET',
              url: 'http://api.football-data.org/v1/competitions/426/leagueTable',
              headers:{
                  'X-Auth-Token': '3e629af30fce46edaa6ead20e007a276'
              }
            })
        }  
      }
})

选择哪种方法取决于您,some docs可以帮助您做出决定。