David Nugent David Nugent - 2 months ago 18
AngularJS Question

Angular app http call custom service failing

I'm making a little angular app to show info about the english premier league. I want to make a service to deal with making http calls cos I do it a few times on the page and I don't want to repeat everything. Here is my table.js TableController, which is used for building a league table/

(function(){

angular
.module("eplApp")
.controller("tableCtrl", TableController);

TableController.inject = ['httpService'];

function TableController(service){
var apiUrl = "http://api.football-data.org/v1/soccerseasons/426/leagueTable";

service.getListFromUrl(apiUrl).then(function(data){
var vm.this;
vm.data = response.data;
});
}
})();


And here is the service I've made to run the http requests, service.js:

(function(){

angular
.module("eplApp")
.factory("httpService", httpService);

httpService.inject = ['$http'];

function httpService($http){
var apiKey = '971acba677654cdb919a7ccebd5621e2';
var vm = this;
vm.data = [];

$http({
headers: { 'X-Auth-Token': apiKey },
method: "GET",
url: apiUrl
}).then(function(response) {
vm.data = response.data;
return vm.data;
});
}
})();


When I run it I get the following error:

Error: [$injector:unpr] http://errors.angularjs.org/1.5.8/$injector/unpr?p0=serviceProvider%20%3C-%20service%20%3C-%20tableCtrl


Where am I going wrong here?

Answer

Try with change your service like that:

(function(){

    angular
    .module("eplApp")
    .factory("httpService", httpService);

    httpService.$inject = ['$http'];

    function httpService($http){
     return {
       getListFromURL : getListFromURL
     }

     function getListFromURL(apiUrl){
      var apiKey = '971acba677654cdb919a7ccebd5621e2';
      var vm = this;
      vm.data = [];

      return $http({
       headers: { 'X-Auth-Token': apiKey },
       method: "GET",
       url: apiUrl
      }).then(function(response) {
        vm.data = response.data;
        return vm.data;
      });
    }
})();

And call the function in controller like this:

TableController.$inject = ['httpService'];

function TableController(service){
  var apiUrl = "http://api.footballdata.org/v1/soccerseasons/426/leagueTable";

  service.getListFromURL(apiUrl).then(function(data){
    //data here is vm.data
  });
}

Hope this help !

Comments