Rawle Juglal Rawle Juglal - 3 months ago 22
AngularJS Question

converting an ajax request to angular $http

I'm learning how to use angular and I'm not really that familiar with making request to an api. I'm trying to practice using http://api.football-data.org/index. The json data I wanted to get from my angular factory is http://api.football-data.org/v1/competitions/426/leagueTable. Right now I'm getting an error in the console


'angular.js:13920 TypeError: Cannot read property 'getLeagueData' of undefined at new ...'


My CLI shows that I am loading all my script files and I tested my controller before trying to bring in the factory and creating the getLeagueData function and it was working so I know my issue is after creating the basic controller. I thought it might have to do with my headers needing the authentification token I received but I'm not sure if I haven't added it correctly. Here is my code

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>





Module

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


Controller

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


Factory

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


The original ajax code sample that the api shows for using it looks like this

$.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);
});

Answer

You used the array notation at your factory. Either use it directly or declare the $http in the array:

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'
              }
            })
        }  
      }
})

Which approach to choose is up to you, there is some docs to assist you on your decision.